简体   繁体   中英

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 eg

    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.

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)'

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

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

This works

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