在字符串中查找每个RegEx匹配项
我喜欢做类似的事情
foreach (Match match in regex) { MessageBox.Show(match.ToString()); }
谢谢你的帮助…!
有一个RegEx.Matches
方法:
foreach (Match match in regex.Matches(myStringToMatch)) { MessageBox.Show(match.Value); }
要获取匹配的子字符串,请使用Match.Value
属性,如上所示。
来自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); }
首先需要声明要分析的字符串,然后声明正则表达式模式。 最后在循环中你必须实例regex.Matches(stringvar)
string stringvar = "dgdfgdfgdf7hfdhfgh9fghf"; Regex regex = new Regex(@"\d+"); foreach (Match match in regex.Matches(stringvar)) { MessageBox.Show(match.Value.ToString()); }