7

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,413
  • 13
  • 67
  • 94

2 Answers2

7
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
  • 313,408
  • 56
  • 485
  • 544
  • 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
  • 7,975
  • 11
  • 51
  • 105
  • 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