Test String:
${$var1} bla ${$var2} bla ${$var2}
\${$var2} bla \\\${$var2} bla $var1
\\${$var1} bla \\${$var2} bla \${$var2}
\\\{$var2} bla \\${$var2} bla \${$var2}
$var1 bla \$var1 bla \\$var1 bla \\\$var1
\$var1 bla \\$var1 bla \\\$var1
\\$var1 bla \\\$var1 bla \$var1 bla
\\\$var1 bla \\$var1 bla \\\$var1
Selection I'm looking for:
I'm looking for a regex to select only ${$varN}, \\${$varN}, $varN, \\$varN
without selecting \${$varN}, \\\${$varN}, \$varN, \\\$varN
Regex I've tried:
(\$\{\$\w*\})|(\$\w*)
but it selects all ${$varN}
and $varN
You can use this regex with a negative lookbehind:
(?<!\\|{)(?:\\\\)*\$(?:{\$)?\w*}?
RegEx Demo
RegEx Description:
(?<!\\|{)
- Negative lookahead to assert we don't have backslash or {
as previous character(?:\\\\)*
- match 0 or more pairs of backslashes\$
- Match a literal $
(?:{\$)?
- Match optional {
followed by $
\w+
- Match 1 or more words}?
- Match optional closing }
Update: If you want more precise matching (one that disallows ${$var3
) then use this advanced PCRE regex that uses if-else-then
construct:
(?<!\\|{)(?:\\\\)*\$({\$)?\w+(?(1)})
RegEx Demo2
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