简体   繁体   中英

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?
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.

您可以在while循环中将“aa”替换为“a”并将其与正则表达式再次匹配,直到没有匹配为止。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM