2014-04-11 70 views
5

如何使用C#中運行的正則表達式找到字符串中的所有匹配項?C#正則表達式匹配字符串中的多個單詞

我想查找下面的示例字符串中的所有匹配項。 實施例:

inputString: Hello (mail) byebye (time) how are you (mail) how are you (time) 

我想從示例匹配(mail)(time)。包括括號()

在試圖解決這個問題時,我寫了下面的代碼。

string testString = @"(mail)|(time)"; 

Regex regx = new Regex(Regex.Escape(testString), RegexOptions.IgnoreCase); 
List<string> mactches = regx.Matches(inputString).OfType<Match>().Select(m => m.Value).Distinct().ToList(); 

foreach (string match in mactches) 
{ 
    //Do something 
} 

是用於邏輯OR條件管道(|)?

回答

6

使用Regex.Escape(testString)是要逃脫你管的性格,轉向

@"(mail)|(time)" 

有效地進入

@"\(mail\)\|\(time\)". 

因此,你的正則表達式是尋找文字"(mail)|(time)"

如果所有的比賽都是由括號包圍的話那麼簡單,我將建立這樣的正則表達式:

List<string> words = new List<string> { "(mail)", "(time)", ... }; 
string  pattern = string.Join("|", words.Select(w => Regex.Escape(w))); 
Regex  regex = new Regex(pattern, RegexOptions.IgnoreCase); 
+0

PERFECT !!!! @FishBasketGordo – Nisho

3

逃生括號中的測試字符串:

string testString = @"\(mail\)|\(time\)"; 

刪除Regex.Escape

Regex regx = new Regex(testString, RegexOptions.IgnoreCase); 

輸出(包括削ntheses)

(mail) 
(time) 

原因Regex.Escape沒有在你的案子是其轉義字符|還有:

轉義最小的一組元字符(\,*,+, ?,|,{,[,(,),^,$,。,#和whitespace)替換它們的\ codes。

+0

哇...正確。但爲什麼使用Escape呢?因爲我想從例如單詞列表中動態生成的TestString: (郵件) (時間) (本) (即) 我以爲可以逃脫他們的期運用Regex.Escape。奇怪的! @Grant Winney – Nisho

+1

我想,因爲它最終會逃避你的'|'角色。 –

+1

@Nisho,通過一切手段使用'Escape',像'String.Join(「|」,myListOfWords.Select(Regex.Escape))''。 – decPL