This will return 4
as you expect:
Regex.Matches("020202020", @"0(?=20)").Count;
The lookahead matches the 20
without consuming it, so the next match attempt starts at the position following the first 0
. You can even do the whole regex as a lookahead:
Regex.Matches("020202020", @"(?=020)").Count;
The regex engine automatically bumps ahead one position each time it makes a zero-length match. So, to find all runs of three 2
's or four 2
's, you can use:
Regex.Matches("22222222", @"(?=222)").Count; // 6
...and:
Regex.Matches("22222222", @"(?=2222)").Count; // 5
EDIT: Looking over your question again, it occurs to me you might be looking for 2
's interspersed with 0
's
Regex.Matches("020202020", @"(?=20202)").Count; // 2
If you don't know how many 0
's there 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 regex:
Regex.Matches("020202020", @"(?=2(?:0*2){2})").Count; // 2