This will return 4 as you expect:
Regex.Matches("020202020", @"0(?=20)").Count;
Looks at 20 without consuming it, so the next match attempt starts at the position following the first 0 . You can even do all regex as a look:
Regex.Matches("020202020", @"(?=020)").Count;
The regular expression engine automatically bends forward one position at every match of zero length. So, to find all runs from three 2 or four 2 , you can use:
Regex.Matches("22222222", @"(?=222)").Count; // 6
... and:
Regex.Matches("22222222", @"(?=2222)").Count; // 5
EDIT: Repeating my question, it seems to me that you can search for 2 , marked 0
Regex.Matches("020202020", @"(?=20202)").Count; // 2
If you don't know how much 0 will be, you can use this:
Regex.Matches("020202020", @"(?=20*20*2)").Count; // 2
And of course, you can use quantifiers to reduce repetition in the regular expression:
Regex.Matches("020202020", @"(?=2(?:0*2){2})").Count; // 2
Alan moore
source share