文本替换小程序

using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Data;
using System.Data.OleDb;

namespace replace
{
	class Program
	{
		static void Main(string[] args)
		{
			//创建日志文件
			string logpath = System.Environment.CurrentDirectory + "//log.txt";
			if (!File.Exists(logpath))
			File.Create(logpath);

			
			//开始替换
			try
			{				
					ReplaceFiles(System.Environment.CurrentDirectory + "//待替换");				
			}
			catch (Exception e)
			{
				System.Windows.Forms.MessageBox.Show("出错");
			}
		}


		/// 
		/// 批量替换文件文本
		/// 
		/// 
		public static void ReplaceFiles(string path)
		{
			string[] fs;
			string[] dirs;
			//是文件
			if (File.Exists(path))
			{
				ReplaceFile(path);
				return;
			}
			//是目录
			if (Directory.Exists(path))
			{
				fs = Directory.GetFiles(path);
				foreach (string f in fs)
				{
					ReplaceFile(f);
				}
				dirs = Directory.GetDirectories(path);
				foreach (string d in dirs)
				{
					ReplaceFiles(d);
				}
				
				return;
			}
		}



		/// 
		/// 替换单个文本文件中的文本
		/// 
		/// 
		/// 
		/// 
		/// 
		/// 
 
 
		public static bool ReplaceFile(string filename)
		{
			FileStream fs = File.OpenRead(filename);
			
			
			//判断文件是文本文件还二进制文件。该方法似乎不科学
			byte b;
			for (long i = 0; i < fs.Length; i++)
			{
				b = (byte)fs.ReadByte();
				if (b == 0)
				{
					System.Windows.Forms.MessageBox.Show(filename+"非文本文件");
					return false;//有此字节则表示改文件不是文本文件。就不用替换了
				}
			}

			//判断文本文件编码规则。
			byte[] bytes = new byte[2];
			Encoding coding = Encoding.Default;
			if (fs.Read(bytes, 0, 2) > 2)
			{
				if (bytes == new byte[2] { 0xFF, 0xFE }) coding = Encoding.Unicode;
				if (bytes == new byte[2] { 0xFE, 0xFF }) coding = Encoding.BigEndianUnicode;
				if (bytes == new byte[2] { 0xEF, 0xBB }) coding = Encoding.UTF8;
			}

			fs.Close();

			//获取替换规则
			DataSet ds = GetReplaceRule();

			//替换数据
			string[] lines = File.ReadAllLines(filename, coding);
			string logpath = System.Environment.CurrentDirectory + "//log.txt";

			string contents = "/r/n/r/n/r/n" + DateTime.Now.ToString() + "在:" + filename + "替换/r/n";
			//content+=lines[i]+" /n ";
			//  File.WriteAllText(logpath, "'"+ content, coding);
			File.AppendAllText(logpath, contents, coding);



			for (int i = 0; i < lines.Length; i++)
			{
				RegexOptions ops = RegexOptions.None;
				for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
				{
					string search = ds.Tables[0].Rows[j][1].ToString();
					string replace = ds.Tables[0].Rows[j][2].ToString();
					
					//todo 记录日志
					if(Regex.IsMatch(lines[i],search))
					{
						try
						{
			         //   string strOldText = File.ReadAllText(logpath, coding);
							string content = "第" + (i+1) + "行/t";
							content += lines[i] + " /t/t/t将 " + search+" 替换为 "+replace+ "/r/n";
                      //  File.WriteAllText(logpath, "'"+ content, coding);
                        File.AppendAllText(logpath, content, coding);
						}
						catch (Exception e3)
						{
							System.Windows.Forms.MessageBox.Show(e3.ToString());
						}
					}
					lines[i] = Regex.Replace(lines[i], search, replace);
				}
				
			}
			File.WriteAllLines(filename, lines,coding);
			return true;
		}



		/// 
		/// 读取替换规则文件
		/// 
		/// 
 
 
		public static  DataSet GetReplaceRule()
		{
			string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;
               Data Source=" + System.Environment.CurrentDirectory + @"/替换规则/replace_rule.xlsx;Extended Properties=""Excel 12.0;HDR=YES;""";
			DataSet ds = new DataSet();
			OleDbConnection con;
			OleDbDataAdapter myadapter;
			con = new OleDbConnection(connectionString);
			try 
			{
				con.Open();
				myadapter = new OleDbDataAdapter("select * from [Sheet1$]", con);
				myadapter.Fill(ds, "ds");
				myadapter.Dispose();
			}
			 catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
			{
                con.Close();
            } 
				return ds;
			}
	}
}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以通过正则表达式来实现字符替换。例如,将字符串中所有的大写字母替换为小写字母,可以使用以下代码: ``` var str = "AbCDeFG"; str = str.replace(/[A-Z]/g, function(match) { return match.toLowerCase(); }); console.log(str); ``` 输出结果为: ``` "abcdefg" ``` 其中,`/[A-Z]/g` 表示匹配所有的大写字母,并且 `g` 表示全局匹配。`function(match){return match.toLowerCase();}` 表示将匹配到的字符串转换为小写字母。 ### 回答2: 微信小程序的字符替换是指在小程序开发中,对字符串中的某些字符进行替换操作。这个功能在很多场景下都很有用,比如对用户输入的文本进行敏感词过滤,或者对文本中的特殊字符进行修正。 在微信小程序中,可以使用字符串的replace方法进行字符替换。该方法接受两个参数,第一个参数是要替换的字符或字符串,第二个参数是替换成的新字符或字符串。通过调用replace方法,可以将字符串中所有符合条件的字符替换掉。 下面是一个示例代码,用于将字符串中的敏感词替换成星号: ``` // 原字符串 var str = "这是一段包含敏感词的文本,如:***。"; // 敏感词列表 var sensitiveWords = ["***", "****", "***"]; // 将敏感词替换成星号 for (var i = 0; i < sensitiveWords.length; i++) { str = str.replace(sensitiveWords[i], "***"); } console.log(str); // 输出:这是一段包含敏感词的文本,如:***。 ``` 通过上述代码,我们可以将字符串中的敏感词替换成了三个星号。这样,在小程序中用户的输入就可以得到合理的处理,保护用户的隐私和安全。 微信小程序的字符替换功能非常实用,可以满足开发中很多对字符串处理的需求。通过合理运用字符替换,可以提升小程序的用户体验和功能完整性。 ### 回答3: 微信小程序中的字符替换是指在文本中将指定的字符或字符串替换为目标字符或字符串的操作。这个功能在开发微信小程序时经常用到,以下是一个简单的示例: 假设我们有一个字符串变量str,其值为"Hello, World!"。我们想要将其中的"Hello"替换为"Hi",可以使用如下代码实现: ```javascript var str = "Hello, World!"; var newStr = str.replace("Hello", "Hi"); console.log(newStr); // 输出:Hi, World! ``` 在上述代码中,replace()函数将str字符串中的"Hello"替换为"Hi",并将结果赋值给newStr变量。最后,我们使用console.log()将newStr的值输出到控制台。运行该代码后,我们可以看到控制台输出了替换后的结果"Hi, World!"。 此外,replace()函数还可以接受正则表达式作为参数,从而实现更加灵活的字符替换。例如,我们可以用以下代码将字符串中所有的数字替换为"X": ```javascript var str = "I have 123 apples."; var newStr = str.replace(/\d+/g, "X"); console.log(newStr); // 输出:I have X apples. ``` 在上述代码中,使用正则表达式/\d+/g匹配所有的数字,并将其替换为"X"。这样,原来的字符串中的数字"123"被替换为"X",最终输出结果为"I have X apples."。 总之,微信小程序中的字符替换可以通过调用replace()函数实现,使用简单的字符串替换或更复杂的正则表达式替换,以实现特定的需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值