【问题标题】:How to find multiple occurrences with regex groups?如何使用正则表达式组查找多次出现?
【发布时间】:2011-03-15 20:16:57
【问题描述】:

为什么会出现以下代码:

“the”有 1 个匹配项

而不是:

“the”有 3 个匹配项

using System;
using System.Text.RegularExpressions;

namespace TestRegex82723223
{
    class Program
    {
        static void Main(string[] args)
        {
            string text = "C# is the best language there is in the world.";
            string search = "the";
            Match match = Regex.Match(text, search);
            Console.WriteLine("there was {0} matches for '{1}'", match.Groups.Count, match.Value);
            Console.ReadLine();
        }
    }
}

【问题讨论】:

    标签: c# regex


    【解决方案1】:
    string text = "C# is the best language there is in the world.";
    string search = "the";
    MatchCollection matches = Regex.Matches(text, search);
    Console.WriteLine("there was {0} matches for '{1}'", matches.Count, search);
    Console.ReadLine();
    

    【讨论】:

      【解决方案2】:

      Regex.Match(String, String)

      在指定的输入字符串中搜索指定正则表达式的第一次出现。

      请改用Regex.Matches(String, String)。

      在指定的输入字符串中搜索所有出现的指定正则表达式。

      【讨论】:

        【解决方案3】:

        Match 返回 第一个 匹配项,请参阅this 了解如何获取其余部分。

        您应该改用Matches。然后你可以使用:

        MatchCollection matches = Regex.Matches(text, search);
        Console.WriteLine("there were {0} matches", matches.Count);
        

        【讨论】:

          【解决方案4】:

          如果你想返回多个匹配项,你应该使用Regex.Matches 而不是Regex.Match。

          【讨论】:

            猜你喜欢
            • 2013-09-29
            • 1970-01-01
            • 2017-05-25
            • 1970-01-01
            • 1970-01-01
            • 2015-09-19
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多