Given these two Regex:
(?!^)\G
and
\G(?!^)
What's the difference between negative lookahead after and before \G
anchor?
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.
^
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”.
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.
\G
and negative lookahead are completely orthogonal. Each one does what it is supposed to do regardless of the presence of the other.\K(?=.*\d)foo
vs(?=.*\d)\Kfoo
?