0

Say i have a string like this: "23423423" and i want to find all numbers with length of 2 with regex like this "[0-9]{2}"

Now in my texteditor this gives me 7 matches: 23, 34, 42, 23, 34, 42, 23

however in c# i seem to be only getting 4 23, 42, 34, 42

I need the first scenario but cannot find a solution.

I have tried regex.Match() and regex.Matches() with no luck.

Anyone know how?

Schotime
  • 15,707
  • 10
  • 46
  • 75
  • The regex as given will match exactly as C# has shown, will see what we can do to cause the regex to step back 1 char and start matching again. – Lazarus Aug 19 '09 at 15:29

3 Answers3

5

This question has some solutions to a very similar problem, and, adapting the simplest one of them, you could use something like:

Regex regexObj = new Regex("\d\d");
Match matchObj = regexObj.Match(subjectString);
while (matchObj.Success) {
    matchObj = regexObj.Match(subjectString, matchObj.Index + 1); 
}
Community
  • 1
  • 1
Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
0

Solving this would be much easier using string manipulation.

aviraldg
  • 9,531
  • 6
  • 41
  • 56
0
(?=([0-9][0-9])).

Use that regex with the Matches() method, then retrieve the matched number by calling Group(1) on each of the Match objects.

But what editor are you using, and how did you get it to perform overlapping matches? That's not the normal behavior for any editor I've used.

Alan Moore
  • 73,866
  • 12
  • 100
  • 156