【问题标题】:PowerShell: Remove Text from Variable using WildcardPowerShell:使用通配符从变量中删除文本
【发布时间】: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


【解决方案1】:
$pattern = [regex]"(Warning123).*(object.)"

$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.'

$FinalOutput = ($FinalOutput -replace $pattern, "")

输出: PS C:\> $FinalOutput Ignoring. Error Found: Sending error to output.

试试看!

【讨论】:

  • 这非常接近,但我不想包括“忽略”部分。我只想留下“发现错误:将错误发送到输出”。我知道这很痛苦,但由于人类可能会阅读此日志,因此我需要维护有助于提高可读性的 $FinalOutput = ($FinalOutput -replace "Warning123", "'nWarning123")
  • 所以看看我的正则表达式。这真的很简单。它正在寻找Warning123object. 以及介于两者之间的所有内容。所以试试$pattern = [regex]"(Warning123).*(Ignoring.)"
  • 啊,我明白了。我认为 Object 是一个非常具体的 RegEx 参数,而不仅仅是一般的“字符串”。谢谢楼主!
猜你喜欢
  • 1970-01-01
  • 2013-10-10
  • 2014-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多