Marc Fauser
Marc Fauser

Reputation: 161

PowerShell/C# regex multiline replace returns wrong line ending

I have a textfile with CRFL line endings, I read the whole file with $c = Get-Content -Raw file.txt the file contains e.g.

    exec Add a, b, c
    exec Rem e, f, g

I try to replace it with my regex $c = $c -replace '(?m)^([ \t])(@exec@)([ \t]+)([a-zA-Z0-9_-]+)(.)$' '$1call$3$4($5)' This doesn't work and I don't know why but to get it working I need to run $c = $c -replace '(?m)^([ \t])(@exec@)([ \t]+)([a-zA-Z0-9_-]+)(.)\r\n?$' '$1call$3$4($5)' and the result is

    call Add(a, b, c
)
    exec Rem(e, f, g
)

with a LF after the ) bracket. I would expect to get

    call Add(a, b, c)
    exec Rem(e, f, g)

with CRLFs

What's wrong with PowerShell and $ and CRLF? Can anybody tell me how to get the correct results? Thanks.

Upvotes: 0

Views: 71

Answers (2)

Marc Fauser
Marc Fauser

Reputation: 161

I found the "bug" and a solution. The $ at the end is not working with MS regex

(?m)^...\r\n

This works

Upvotes: 1

scaler
scaler

Reputation: 574

I could not get your regex to match anything but this more generic replace should do the trick:

-replace  '(?m)^(\s*)([^\s]*)(\s*)([^\s]*)(\s*)(.*)$', '$1call$3$4$5($6)'

Upvotes: 0

Related Questions