首页 > 解决方案 > 为什么 -replace 不能像这个 powershell 脚本中描述的那样工作?

问题描述

allacts.txt 中的输入文本是:

institutionId: blah blah,name: 1st thing,laestabNo: blah blah   institutionId: blah blah,name: 2nd thing,laestabNo: blah blah, [lots more things]   institutionId: blah blah,name: last thing,laestabNo: blah blah

所需的输出是:

1st thing,laestabNo: blah blah  2nd thing,laestabNo: blah blah, [lots more things]  last thing,laestabNo: blah blah

我在 powershell 脚本中使用的命令:

Powershell -NoProfile "(Get-Content -Raw .\allacts.txt) -replace 'institutionid.*,name', '' | Out-File -FilePath allacts.txt -Force -Encoding ASCII"

我实际得到的是:

last thing,laestabNo:blah blah

没有别的了。我究竟做错了什么?

标签: powershell

解决方案


您的正则表达式不适合您的用例。你是这个意思...

$SomeString = 'institutionId: blah blah,name: 1st thing,laestabNo: blah blah   institutionId: blah blah,name: 2nd thing,laestabNo: blah blah, [lots more things]   institutionId: blah blah,name: last thing,laestabNo: blah blah'
Clear-Host
# RegEx to replace all text string patterns and the text between them
$SomeString -Replace '(institutionId: ).*?(name: )'
# Results
<#
1st thing,laestabNo: blah blah   2nd thing,laestabNo: blah blah, [lots more things]   last thing,laestabNo: blah blah
#>

推荐阅读