Regex that will match PHP variable but not object and function invocation

jcubic

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.

Wiktor Stribiżew

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:

enter image description here

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How to match PHP tags with Regex?

From Dev

PHP Regex to match an IP address

From Dev

Simple regex to match word in the format variable = [[ word ]] in php

From Dev

RegEx - JavaScript .match() with a variable keyword

From Dev

PHP: Regex: Match if doesnt contain

From Dev

Regex to match a variable in Batch scripting

From Dev

SSRS Function with Regex Match

From Dev

Get return value of first function invocation match without invoking it twice

From Dev

Bash regex string variable match

From Dev

PHP - preg_match regex

From Dev

Match the body of a function using Regex

From Dev

PHP regex - pattern does not match

From Dev

get a string php regex match

From Dev

PHP Match Multipline Line with Regex

From Dev

regex match in PHP

From Dev

RegEx - JavaScript .match() with a variable keyword

From Dev

PHP regex match multiple pieces

From Dev

Regex to match a function

From Dev

PHP/Regex - Warning: preg_match_all() [function.preg-match-all]: Unknown modifier

From Dev

PHP Regex Match nothing

From Dev

SSRS Function with Regex Match

From Dev

Get return value of first function invocation match without invoking it twice

From Dev

PHP Access a variable inside a function of an object in an object of this object

From Dev

Bash regex string variable match

From Dev

Regex that will match PHP variable but not object and function invocation

From Dev

Java regex to match for variable value

From Dev

Regex match for object creation in Java

From Dev

filter function using match with regex

From Dev

JavaScript - Regex Match Not a Function