如何使用正则表达式组查找多个匹配项?

36

为什么以下代码的结果是:

有 1 个匹配结果符合 “the”

而不是:

有 3 个匹配结果符合 “the”

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();
        }
    }
}
4个回答

63
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();

21

7

Match会返回第一个匹配项,参见此文档以获取后续匹配项。

建议使用Matches。您可以使用以下代码:

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

3

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接