powershell regex check if file has word wrapped in special characters

Viewed 88

I need to match text in a file that contains a variable wrapped in special characters.

Ex:

#{VARIABLE_A}#

#{VARIABLE_A_EXAMPLE}#

it should NOT match these

#{VARIABLEA}#

#{_VARIABLE_A}#

#{_VARIABLE_A_}#

#{VARIABLE_A

  VARIABLE_A}#

#{}#
#{_}#

what I tried

#{\w{3}}#
/\w+\#{[}#]+)\)/g
#\\w+\\b
#{\w+}#

Can someone explain how the answer is derived

1 Answers

You can use

#{[a-zA-Z]+(?:_[a-zA-Z]+)+}#

If digits are allowed you can add 0-9 into the character classes, or you may use [^\W_] that matches any word char other than _:

#{[a-zA-Z0-9]+(?:_[a-zA-Z0-9]+)+}#
#{[^\W_]+(?:_[^\W_]+)+}#

See the regex demo.

Details

  • #{ - a #{ substring
  • [a-zA-Z]+ - one or more letters
  • (?:_[a-zA-Z]+)+ - one or more occurrences of _ and one or more letters
  • }# - a }# substring
Related