开发者

regex matches with intersection in C#

开发者 https://www.devze.com 2022-12-28 00:56 出处:网络
I wonder if it is possible to get MatchCollection with all matches even if there\'s intersection among them.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消