I want to match variables inside a string, which are addressed using the dollar symbol $. However, my regex expression should not match character sequences following an escaped dollar symbol (e.g. escaped with the backslash \$).
If a backslash is escaped with an other one (\\), the following variable should of course be matched.
TL;DR: Any sequence $xxxxxshould be matched, only if it follows a even count of backslashes \ (0, 2, 4, 6, ...). The backslashes themselves should not be part of the capture group.
I currently have the following expression: (?:[^\\]*(\\{2})*)(\$[a-z_]\w*\b),
but it does not work correctly on the following text (of course with the options \igm):
Hello $var, this is a backslash followed by a dollar: \\\$
$test \$escaped \\$not_escaped \\\$escaped_again \\\\$you_get_the_idea
The matched 'variables' should be $var, $test, $not_escaped and $you_get_the_idea.
However, https://regex101.com displays other matches.
I cannot get my head around the error.
Using this regex with a lookbehind assertion, you can capture the variable strings in group 1:
(?<!\\)(?:\\\\)*(\$\w+)
Demo on regex101.com
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With