4

Given these two Regex:

(?!^)\G

and

\G(?!^)

What's the difference between negative lookahead after and before \G anchor?

3
  • 2
    I don't get this question. \G and negative lookahead are completely orthogonal. Each one does what it is supposed to do regardless of the presence of the other.
    – Jon
    Apr 28, 2014 at 10:10
  • 2
    I'm wondering why you are posting such non-practical questions? Can I expect a third one like \K(?=.*\d)foo vs (?=.*\d)\Kfoo?
    – HamZa
    Apr 28, 2014 at 10:19
  • 2
    For those who are interested, here's a pcretest dump, note that it might be different with .net. I suspect that the chance would be very small...
    – HamZa
    Apr 28, 2014 at 10:31

2 Answers 2

2

They are exactly the same, since we are going to check completely orthogonal logical conditions. Indeed, in both examples the negative lookahead

(?!^)

is combined with the anchor

\G

Hence, we are asking for something which at the same time is

  • at the end of the previous match or at the start of the string for the first match

  • not followed by anything which is at the start of the string.

24
  • 2
    ^ does not check for characters. It checks for the beginning of the string. Of course (?!^) can fail to match. It means (the equivalent of) “we are not at the beginning of the string”.
    – Timwi
    Apr 28, 2014 at 10:13
  • Nope, it means “what follows us cannot be at the beginning of the string”. Apr 28, 2014 at 10:14
  • 1
    That is logically the same as what I said :)
    – Timwi
    Apr 28, 2014 at 10:16
  • (?!^)abc won't match the first abc in abcabc
    – Robin
    Apr 28, 2014 at 10:17
  • I’m going to take a stab in the dark here and suspect and that you downvoted my answer out of spite. Please do not do this. Only downvote answers that are wrong.
    – Timwi
    Apr 28, 2014 at 10:20
1

Logically, they come out to be the same thing. They are functionally equivalent. The (?!^) and the \G check two different conditions at the same location in the string, so it makes no logical difference what order the conditions are checked in.

The conditions are:

  • (?!^) = “we are not at the beginning of the input string”
  • \G = “we are in the location where the previous match ended”

However, in terms of performance, I suspect (though I haven’t tested) that the latter is faster. I would expect the regular expression engine to have an optimisation so that a regex that starts with \G would only be executed from the previous match’s end onwards, while the other one would go through the whole string “looking for” the location of the previous match.

Your Answer

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

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