简体   繁体   中英

Powershell Regex matches leading and trailing spaces

I would like to match with Powershell -replace all $test occurrences that are not quoted (line 3, 4, 6, 7 in the sample below)

1) '$test'
2) test
3) $test
4) foo $test bar
5) foo '$test' bar
6) foo "$test" foo
7) "$test"

I used the regexp below

'[^\'']\$test[^\'']'

but this matches the space too, for example in the line 4, causing the replace to trim them.

How can I match exactly $test when not embedded in single quotes?

You could use the below regex to match $test in the lines 3,4,6,7(ie, $test not enclosed within single quotes)

(?<!\')\$test(?!\')

DEMO

Explanation:

  • (?<!\\')\\$test Negative lookahead, which ensures that it won't match the string $test present just after to the single quote.
  • (?!\\') And the following character wouldn't be a single quote. Regex engine match the string $test only if the both conditions are satisfied.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM