tags:

views:

116

answers:

4

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?

+4  A: 

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); 
}
Alex Martelli
A: 

Solving this would be much easier using string manipulation.

Aviral Dasgupta
A: 

Would it look like this?

([0-9])(?=([0-9]))

I ran that through Derek Slager's .NET Regular Expression Tester and it seemed to come out with what you want.

Sterno
Regexbuddy shows that your regexp would only give 23, 42, 34, 42. The expression with positive lookahead would be ([0-9])(?=([0-9])) with combining groups 1 and 2 on each consequtive match as shown in the answers to the question Alex Martelli links to.
axk
Ah, good call. I think I was reading the results of that web page wrong.
Sterno
A: 
(?=([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