2011-04-02 85 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); 
    }