Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negate multiple words

Tags:

regex

perl

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

like image 947
Omar Avatar asked Oct 18 '22 17:10

Omar


1 Answers

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

like image 200
anubhava Avatar answered Oct 20 '22 21:10

anubhava