【发布时间】:2021-10-05 08:17:12
【问题描述】:
我正在阅读有关在 -replace 对象 here 中使用 RegEx 的信息,但解决方案和问题并不是我所面临的。
如果我有以下变量:
$FinalOutput = Warning123 for Item: XYZ. Cannot specify "specific" object. Ignoring. Warning123 for Item: ABC. Cannot specify "specific" object. Ignoring. Error Found: Sending error to output.
然后使用简单的-replace 将变量从全内联更改为单行:
$FinalOutput = ($FinalOutput -replace "Warning123", "`nWarning123")
我现在被困住了:
Warning123 for Item: XYZ. Cannot specify "specific" object. Ignoring.
Warning123 for Item: ABC. Cannot specify "specific" object. Ignoring.
Error Found: Sending error to output.
我的变量总是会有警告,我希望删除那些以Warning123 开头的值。几乎就像我写了$FinalOutput = ($FinalOutput -replace "Warning123*", "")。但是,通配符在 -replace 对象中不起作用。我的最终结果应该是这样的:
$FinalOutput
Error Found: Sending error to output.
Using RegEx,我想我可以用我的特定短语捕获字符串的开头,然后不忠删除该字符串后面的字符,让我一无所有:
^.*?Warning123 for Item:(.*)
但是,这似乎也不起作用。对此解决方案有任何想法或帮助吗?
【问题讨论】:
-
您的预期输出是什么?所有没有以
Warning123开头的句子?试试^\s*Warning123 for Item:([^.]*)\.\s*,见regex101.com/r/1iG1og/3 -
你能在
Error Found:上拆分,从拆分中获取最后一项,然后修剪结果吗? -
@WiktorStribiżew 是的,预期的输出是删除 Error Found 行以外的所有内容。
-
@Lee_Dailey Split 在这里对我没有帮助,因为它会将其放入数组中。
-
啊哈,所以你需要
^(?!\s*Warning123 for Item:).+或^(?!\s*Warning123 for Item:).*\n?
标签: regex powershell