我想知道是否有可能获得包含所有匹配项的MatchCollection,即使它们之间存在交集。
string input = "a a a";
Regex regex = new Regex("a a");
MatchCollection matches = regex.Matches(input);
Console.WriteLine(matches.Count);
这段代码返回1,但我想让它返回2。如何实现?
谢谢您的帮助。
string input = "a a a";
Regex regexObj = new Regex("a a");
Match matchObj = regexObj.Match(input);
while (matchObj.Success) {
matchObj = regexObj.Match(input, matchObj.Index + 1);
}
将从上一次匹配的位置的下一个字符开始迭代字符串,因此找到所有匹配项。
你可以使用 while 循环,通过将 "a a" 替换为 "a" 并再次与正则表达式匹配,直到没有匹配项。