regex matches with intersection in C#
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开发者_JAVA百科?
Thank you for your help.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.
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.
精彩评论