如何在c#.net中使用正则表达式?

时间:2010-11-24 06:19:22

标签: c# .net

我想在文本文件的内容中找到特定的模式。任何人都可以帮我编写如何使用正则表达式(带语法)在c#.net中实现它?

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

这基本上取决于您想要识别的模式。正如其他人所说,您应该更加具体地了解您的模式期望。

首先,您需要获得正则表达式语法的基本知识(通常是POSIX,历史上是UNIX,但它是跨语言/平台语法):看看this reference site

然后转到您最喜欢的c#编辑器并输入:

using System.Text.RegularExpressions;

StreamReader sr = new StreamReader(yourtextfilepath);
string input;
string pattern = @"\b(\w+)\s\1\b";//Whatever Regular Expression Pattern goes here
while (sr.Peek() >= 0)
{
   input = sr.ReadLine();
   Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
   MatchCollection matches = rgx.Matches(input);
   if (matches.Count > 0)
   {          
      foreach (Match match in matches)
         //Print it or whatever 
         Console.WriteLine(match.Value);
   }
}
sr.Close();