2011-04-02 87 views
14

ID喜歡做這樣的事情字符串查找每個正則表達式匹配

foreach (Match match in regex) 
    { 
    MessageBox.Show(match.ToString()); 
    } 

感謝您的幫助...!

+0

你能告訴一個例子輸入和輸出? – kennytm 2011-04-02 18:54:47

+1

對於我們這些懶得查看它並且不知道的人:RegularExpressions位於System.Text命名空間中。 – amalgamate 2015-04-17 15:23:55

回答

31

有一個RegEx.Matches方法:

foreach (Match match in regex.Matches(myStringToMatch)) 
{ 
    MessageBox.Show(match.Value); 
} 

爲了獲得匹配的子串,使用Match.Value屬性,如上所示。

+0

@kojoma - 你提供了一個參數到'Matches'方法嗎? – Oded 2011-04-02 19:03:57

+0

對不起,是一個錯字,這個作品發現!謝謝! – kojoma 2011-04-02 19:06:43

4

您首先需要聲明要分析的字符串,然後是正則表達式模式。 最後,在循環中,您必須實例regex.Matches(stringvar)

string stringvar = "dgdfgdfgdf7hfdhfgh9fghf"; 
Regex regex = new Regex(@"\d+"); 

foreach (Match match in regex.Matches(stringvar)) 
{ 
    MessageBox.Show(match.Value.ToString()); 
} 
9

MSDN

string pattern = @"\b\w+es\b";  
    Regex rgx = new Regex(pattern);  
    string sentence = "Who writes these notes?"; 

    foreach (Match match in rgx.Matches(sentence)) 
    { 

    Console.WriteLine("Found '{0}' at position {1}", 
         match.Value, match.Index); 
    }