Sudhar
Sudhar

Reputation: 3

why this regex does not work in powershell?

$pattern = 'trigger(.+?)(\r|\n|\r\n){2}'
Write-Host "PATTERN $pattern"
Write-Host ("- trigger: blah`n blah`n blah blah`n`n not blah" -replace $pattern, "trigger: none")

Output should be "- trigger: none not blah"

Upvotes: 0

Views: 45

Answers (1)

wp78de
wp78de

Reputation: 18950

There are two problems:

  • .+ matches everything except for newlines, use the inline flag (?s) or a modified dot [\S\s]+
  • \r\n is the Windows line break and \n *unix; therefore it is best to make \r optional ?: (\r?\n)
$pattern = 'trigger([\s\S]+?)(\r?\n){2}'
Write-Host "PATTERN $pattern"
Write-Host ("- trigger: blah`n blah`n blah blah`n`n not blah" -replace $pattern, "trigger: none")

- trigger: none not blah

Upvotes: 1

Related Questions