I am working on a regex that will match one of
$foo $bar $baz
but not
$foo->bar
So far, I have
/\$([a-zA-Z_][a-zA-Z_0-9]*(?!->))/
Unfortunately, this pattern matches $fo
. See this regex demo.
Use a possessive quantifier that will disallow backtracking into the [a-zA-Z_0-9]
subpattern:
\$([a-zA-Z_][a-zA-Z_0-9]*+(?!->))
^^
or even (as [a-zA-Z_0-9]
= \w
if you are not using /u
modifier or (*UCP)
verb):
\$([a-zA-Z_]\w*(?!->))
See regex demo
The issue is that when the negative lookahead fails backtracking gets into play, and as *
allows backtracking into the quantified subpattern, the o
that is not followed with ->
is found and a match is returned.
See how your regex works, pay special attention at the backtracking steps:
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments