【问题标题】:Find each RegEx match in string查找字符串中的每个 RegEx 匹配项
【发布时间】:2011-04-02 18:53:16
【问题描述】:

我喜欢做类似的事情

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

感谢您的帮助...!

【问题讨论】:

  • 你能展示一个输入和输出的例子吗?
  • 对于我们这些懒得查,不知道的人:RegularExpressions 在 System.Text 命名空间中。

标签: c# regex


【解决方案1】:

有一个RegEx.Matches方法:

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

要获取匹配的子字符串,请使用Match.Value 属性,如上所示。

【讨论】:

  • @kojoma - 您是否为Matches 方法提供了参数?
【解决方案2】:

来自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);
  }

【讨论】:

    【解决方案3】:

    您首先需要声明要分析的字符串,然后是正则表达式模式。 最后在循环中你必须实例化regex.Matches(stringvar)

    string stringvar = "dgdfgdfgdf7hfdhfgh9fghf";
    Regex regex = new Regex(@"\d+");
    
    foreach (Match match in regex.Matches(stringvar))
    {
        MessageBox.Show(match.Value.ToString());
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-22
      • 1970-01-01
      • 2014-08-05
      • 1970-01-01
      • 2023-01-06
      • 2012-07-27
      • 1970-01-01
      相关资源
      最近更新 更多