2

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

1 Answer 1

1

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.

4
  • Thanks, thats a nice and clever workaround. The only thing I need to do is to append "0" to the end of the match string. Do You think, that this is the only solution?
    – patex1987
    Commented Sep 24, 2016 at 23:44
  • I think the lookahead solution is the simplest one here (again, provided that your regex engine supports that).
    – redneb
    Commented Sep 24, 2016 at 23:49
  • 1
    If the regex engine supports lookaheads, a "better" solution is (?=(0\.{1,3}0)) (since all the values will be captured into Group 1 and there won't be any need adding 0s at the end). It is a bit slower than redneb's pattern. Commented Sep 24, 2016 at 23:53
  • Yes its working in Python and Notepad++ as well. So actually my problem is solved
    – patex1987
    Commented Sep 25, 2016 at 0:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.