8

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.

StuffHappens
  • 6,457
  • 13
  • 70
  • 95

2 Answers2

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

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • Seems like what i need. Thanks. – StuffHappens Apr 20 '10 at 12:42
  • +1 Very nice I was going to recommend something similar with string.indexOf assuming that the search string was a vanilla string. I'm wondering if there's a complex regex that this method wouldn't work for.....hmmm – juharr Apr 20 '10 at 12:45
0

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.

Jerome Cance
  • 8,103
  • 12
  • 53
  • 106
  • This example is simplified. I have much more complex input string and much more complex regex. So your solution won't work in that case. Thanks anyway. – StuffHappens Apr 20 '10 at 12:38