Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex matches with intersection in C#

Tags:

c#

regex

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.

like image 317
StuffHappens Avatar asked Apr 20 '10 12:04

StuffHappens


People also ask

Can you use intersection in regular expressions?

Intersection is not a part of standard regular expressions.

What is intersection in regex?

The intersection of several regexes is one regex that matches strings that each of the component regexes also match. The General Option. To check for the intersection of two patterns, the general method is (pseudo-code): if match(regex1) && match(regex2) { champagne for everyone! }


1 Answers

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.

like image 66
Tim Pietzcker Avatar answered Oct 19 '22 09:10

Tim Pietzcker