views:

160

answers:

3

Regex.Match has a .Success and .NextMatch why doesnt it have a GetEnumerator function?

With my logic it seems easy enough to implement. But it isnt in 3.5 so can anyone tell me why not?

foreach (var m in Regex.Match("dummy text", "mm")) error CS1579: foreach statement cannot operate on variables of type 'System.Text.RegularExpressions.Match' because 'System.Text.RegularExpressions.Match' does not contain a public definition for 'GetEnumerator'
+8  A: 

Perhaps you want Regex.Matches?

Mark Byers
+2  A: 
Regex.Match

returns the first instance of the pattern that is matched in the string.

You probably want

Regex.Matches

, which returns a MatchCollection of all the matches in the string.

MSDN Article on Regex.Match

Joseph
+2  A: 

Because the Match object is immutable (and NextMatch() does not change the context of the current match, but gives you a reference to the next one, which is different from IEnumerable.MoveNext() ).

But you can do this:

for (Match m=Regex.Match("dummy text", "mm"); m.Success; m=m.NextMatch()) {
    // loop code
}
Lucero
Ahh its immutable +1. And +1 for everyone else bc they mentioned matches.
acidzombie24