如何使用正则表达式组查找多个事件?

Edw*_*uay 24 c# regex

为什么以下代码会导致:

'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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Dra*_*ter 45

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();
Run Code Online (Sandbox Code Playgroud)


Ama*_*osh 14

Regex.Match(String,String)

在指定的输入字符串中搜索指定正则表达式的第一个匹配项.

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

在指定的输入字符串中搜索指定正则表达式的所有匹配项.


Laz*_*rus 6

Match返回第一场比赛,有关如何获得其余比赛,请参阅this

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

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