patex1987
patex1987

Reputation: 417

Regex - some matches are missing

I am trying to solve a really simple problem,but I cant find any solution. My string looks like this: "...0.0..0.0..."

My regex is: 0[.]{1,3}0

I am expecting 3 matches: 0.0, 0..0, 0.0 But instead of that I am getting only two matches: 0.0 and 0.0. Can You please tell me what

Upvotes: 2

Views: 197

Answers (1)

redneb
redneb

Reputation: 23850

The problem is that when the regex matches the first time, it consumes the characters from the input string that it has matched with. So in first match, it matches with:

...0.0....0.0...
   ^^^

so then for the next match it will consider the remainder of the string which is

....0.0...

and there, as you can see, it will only find a single match.

One way around this issue is to use a zero width lookahead assertion, provided that your regex engine supports that. So your regex would look like

0[.]{1,3}(?=0)

The meaning of this is that it will match the 0 at the end but it will not consume it. The issue with this approach is that it will not include that 0 in the matches. One solution for this issue is add the 0 afterwards yourself.

Upvotes: 1

Related Questions