为什么会出现以下代码:
'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();
}
}
}
答案 0 :(得分:41)
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();
答案 1 :(得分:14)
答案 2 :(得分:4)
Match
返回第一个匹配,请参阅this了解如何完成剩下的工作。
您应该使用Matches
代替。然后你可以使用:
MatchCollection matches = Regex.Matches(text, search);
Console.WriteLine("there were {0} matches", matches.Count);
答案 3 :(得分:3)
如果您想要返回多个匹配项,那么您应该使用Regex.Matches
而不是Regex.Match
。