可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I wonder if it is possible to get MatchCollection with all matches even if there's intersection among them.
string input = "a a a"; Regex regex = new Regex("a a"); MatchCollection matches = regex.Matches(input); Console.WriteLine(matches.Count);
This code returns 1, but I want it to return 2. How to achive it?
Thank you for your help.
回答1:
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); }
will iterate over the string starting the next iteration one character after the position of the previous match, therefore finding all matches.
回答2:
You can do it in a while loop by replacing "a a" by "a" and match it another time against the regex until there is no match.