C#正则表达式:移除文本中所有方括号和其中的内容
2007-07-29 09:36
253 查看
有一文本文件,内容如下: ....... absent ['1bs4nt, 4b'sent] a.(from)缺席,不在场;漫不经心的 absolute ['1bs4lu:t] a. 绝对的,完全的 absorb [4b's3:b] v. 吸收; 吸引,使专心 abstract ['1bstr1kt] a. 抽象的n. 摘要,提要v. 提(抽)取 ....... 方括号中应该是音标,因为不能正常显示,希望将其删除,总共有5000多个单词,用C#正则表达式,代码如下: using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Text.RegularExpressions; namespace Test { class Program { static void Main(string[] args) { //设置字符编码很重要,否则会得到乱码 StreamReader sr = new StreamReader("c:\\1.txt", System.Text.Encoding.Default); StreamWriter sw = new StreamWriter("c:\\2.txt",false , System.Text.Encoding.Default); using(sr) using(sw) { String temp=sr.ReadToEnd(); Regex rx = new Regex(@"\[.*\]", RegexOptions.Multiline);//多行模式 temp=rx.Replace(temp, ""); sw.Write(temp); } //Regex Match Group Capture 的用法 //string text = "One car red car blue car"; //string pat = @"(?<1>\w+)\s+(?<2>car)\s*"; /**///// Compile the regular expression. //Regex r = new Regex(pat, RegexOptions.IgnoreCase); /**///// Match the regular expression pattern against a text string. //Match m = r.Match(text); //while (m.Success) //{ // // Display the first match and its capture set. // System.Console.WriteLine("Match=[" + m + "]"); // CaptureCollection cc = m.Captures; // foreach (Capture c in cc) // { // System.Console.WriteLine("Capture=[" + c + "]"); // } // // Display Group1 and its capture set. // Group g1 = m.Groups[1]; // System.Console.WriteLine("Group1=[" + g1 + "]"); // foreach (Capture c1 in g1.Captures) // { // System.Console.WriteLine("Capture1=[" + c1 + "]"); // } // // Display Group2 and its capture set. // Group g2 = m.Groups[2]; // System.Console.WriteLine("Group2=[" + g2 + "]"); // foreach (Capture c2 in g2.Captures) // { // System.Console.WriteLine("Capture2=[" + c2 + "]"); // } // // Advance to the next match. // m = m.NextMatch(); //} } } } 1、读写文本文件的时候必须要设置字符编码,否则中文会出现乱码; 2、设置多行模式 |
相关文章推荐
- Python学习笔记——利用Python统计某目录下所有文本中内容行数
- Java去掉字符串中所有的标签,获取纯文本内容
- 输出所有select元素下的所有option元素中对应的文本内容
- vim中剪切多行,粘贴的方法,删除所有文本内容
- python etree 输出某个节点下的所有节点的文本内容
- 找以其中一个字段为不重复记录,但结果要显示所有字段内容
- 遍历一个文件夹下的所有文件,并对其中内容进行去重。
- js中获取匿名函数调用的callee和本js匿名函数中的所有文本内容
- linux下 c语言递归遍历文件夹下所有文件和子文件夹(附上替换文本文件内容的方法)
- Java去掉字符串中所有的标签,获取纯文本内容,获取src
- 建立一个文本文件in.txt,在其中输入若干个正整数,中间用空格分隔,然后保存起来;在窗体上添加一个命令按钮和一个标签框,当单击命令按钮时将in.txt文件中存放的所有的能被3整除的数的和显示在标签框
- GridView中的每个单元格文本长度的控制,鼠标悬停时,显示单元格所有的内容
- detach() 方法移除被选元素,包括所有文本和子节点
- 编写一个程序,从标准输入一行一行地读取文本,并完成如下任务:如果文件中有两行或更多行相邻的文本内容相同,那么就打印其中一行,其余行不打印。
- 从文件中读入文本,文本内容为几个字符串,用逗号间隔,将其中同时含有字母和数字的字符串去除,留下仅仅只包含字母或数字的字符串,然后进行排序
- Linux批量替换文本,文件夹内所有文本内容
- 批处理怎样替换文件夹下所有文本内容?
- 如何从文本中移除空白内容
- c++读入文本所有内容
- jaxp dom-getElementsByTagName xml中得到指定名字的所有标签的文本内容