简体   繁体   English

PowerShell/C# 正则表达式多行替换返回错误的行尾

[英]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我有一个带有 CRFL 行结尾的文本文件,我用 $c = Get-Content -Raw file.txt 读取了整个文件,该文件包含例如

    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我尝试用我的正则表达式替换它 $c = $c -replace '(?m)^([ \t] )(@exec@)([ \t]+)([a-zA-Z0-9_-] +)(. )$' '$1call$3$4($5)' 这不起作用,我不知道为什么,但要让它工作,我需要运行 $c = $c -replace '(?m)^ ([ \t] )(@exec@)([ \t]+)([a-zA-Z0-9_-]+)(. )\r\n?$' '$1call$3$4($5)'结果是

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

with a LF after the ) bracket. ) 括号后有一个 LF。 I would expect to get我希望得到

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

with CRLFs带有 CRLF

What's wrong with PowerShell and $ and CRLF? PowerShell 和 $ 和 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最后的 $ 不适用于 MS 正则表达式

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

This works这有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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