2010-11-24 58 views
-1

我想在文本文件的內容中找到特定的模式。任何人都可以幫助我編碼如何使用regularexpression(帶語法)在c#.net中實現這一點?如何在c#.net中使用RegularExpression?

+2

你將不得不做多一點點比解釋。你有沒有任何IDE的正則表達式的深度? – 2010-11-24 06:21:02

+0

內容的樣本將需要有人在這裏爲你制定一個正則表達式。你也應該用正則表達式來標記這個問題。有關如何在C#中使用該正則表達式的幫助,請查看http://msdn.microsoft.com/zh-cn/library/ms228595(v=VS.100).aspx – basarat 2010-11-24 06:37:41

回答

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();