Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match variables inside string

Tags:

c#

regex

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.

like image 958
unknown6656 Avatar asked Mar 08 '26 15:03

unknown6656


1 Answers

Using this regex with a lookbehind assertion, you can capture the variable strings in group 1:

(?<!\\)(?:\\\\)*(\$\w+)

Demo on regex101.com

like image 73
Patrick Roberts Avatar answered Mar 11 '26 05:03

Patrick Roberts



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!