如何使用正则表达式在 powershell 中删除部分字符串

Fre*_*ter 4 regex powershell

我正在努力解决我无法弄清楚的正则表达式:

我的字符串是这样的

Y

[sudo] Password for user: Other Text here
even more text here: with more text
Run Code Online (Sandbox Code Playgroud)

我的目标是选择从第一行到第一个“:”的所有文本,并将其替换为任何内容。

问题是前两行可能存在也可能不存在,并且仍然必须选择直到并包括第一次出现“:”的文本

我的最终结果应该是这样的:

Other Text here
even more text here: with more text
Run Code Online (Sandbox Code Playgroud)

这就是我得到的,但现在我被困住了:

$Test[0..3] -replace ('[a-zA-Z]+\w\:*\s')
Run Code Online (Sandbox Code Playgroud)

但这留下了第 0 行和第 1 行,并且也没有摆脱 [sudo] :(

希望正则表达式专家能给我一些见解:)

编辑 有关实际字符串的更多信息(非常长并且包含 unix 日志文件):

C:\> $MainArray
y

[sudo] password for User: 1485673353 1 33412 2 appxxx 1801152 1801047 0 appxxx bptm image copy is not ready, retry attempt: 6 of 500 o
bject is busy, cannot be closed
1485673354 1 33412 2 appxxx 1801153 1801047 0 appxxx bptm image copy is not ready, retry attempt: 6 of 500 object is busy, cannot be closed etc. etc.
Run Code Online (Sandbox Code Playgroud)

尝试第一个答案:C:> $MainArray -replace ('^[^:]+?:\s*')

y

1485676476 1 4 4 appxxx 1801540 1801213 0 appxxx bptm successfully wrote backup id appxxx_1485671817, copy 1, fragment 17, 51200000
Run Code Online (Sandbox Code Playgroud)

它以某种方式不会删除前两行( y 和 RETURN )

ssc*_*ep3 5

正则表达式 1 (不包括冒号)

您可以使用这个正则表达式:

^[^:]+?(?=:)
Run Code Online (Sandbox Code Playgroud)
  • ^匹配字符串的开头
  • [^:]+?匹配 1 个或多个字符,但:字符数量尽可能少
  • (?=:)正向前瞻:冒号需要直接位于上一个匹配项之后

regex101的实时示例


正则表达式 2 (包括冒号)

如果你还想匹配冒号和下一个空格,你也可以使用这个正则表达式:

^[^:]+?:\s*
Run Code Online (Sandbox Code Playgroud)
  • :而不是(?=:)在匹配中包含冒号
  • \s*匹配尽可能多的空白字符(0 个或多个空白字符)

regex101的实时示例


带有正则表达式 2 的 PowerShell

$test="[sudo] password for user: other text here. even more text: sdfvsdv"
$test -replace "^[^:]+?:\s*"
Run Code Online (Sandbox Code Playgroud)

其他文字在这里。更多文字:sdfvsdv

powershell控制台

  • 也许包含更多关于此模式为何有效的上下文/解释 (2认同)