Powershell:替换所有以相同 Unicode 字符(正则表达式?)开头的不同子字符串
Powershell: Replace all occurrences of different substrings starting with same Unicode char (Regex?)
我有一个字符串:
[33m[TEST][90m [93ma wonderful testorius line[90m ([37mbite me[90m) which ends here.
你看不到它(因为当我 post 它时 Whosebug 会删除它)但是在每个 [xxm
之前都有一个特殊的 Unicode 字符,其中 xx
是一个变量number 和 [
以及 m
是固定的。您可以在此处找到特殊字符:https://gist.githubusercontent.com/mlocati/fdabcaeb8071d5c75a2d51712db24011/raw/b710612d6320df7e146508094e84b92b34c77d48/win10colors.cmd
所以,它是这样的(特殊字符在这里用$显示):
$[33m[TEST]$[90m $[93ma wonderful testorius line$[90m ($[37mbite me$[90m) which ends here.
现在,我想删除此行中的所有 $[xxm
子字符串,因为它仅用于彩色监视器输出,不应保存到日志文件中。
所以预期的结果应该是:
[TEST] a wonderful testorius line (bite me) which ends here.
我尝试使用 RegEx,但我不明白它(可能由于特殊字符和开放的括号,它更加令人困惑)并且我无法在正常的 .Replace ("this","with_that")
操作中使用通配符。
我怎样才能做到这一点?
在这个简单的例子中,以下 -replace
operation will do, but note that this is not sufficient to robustly remove all variations of ANSI / Virtual Terminal escape sequences:
# Sample input.
# Note: `e is used as a placeholder for ESC and replaced with actual ESC chars.
# ([char] 0x1b)
# In PowerShell (Core) 7+, "..." strings directly understand `e as ESC.
$formattedStr = '`e[33m[TEST]`e[90m `e[93ma wonderful testorius line`e[90m (`e[37mbite me`e[90m) which ends here.' -replace '`e', [char] 0x1b
# \x1b is a regex escape sequence that expands to an ESC char.
$formattedStr -replace '\x1b\[\d*m'
一般来说,建议在生成此类用于显示格式的字符串的程序上寻找选项,使它们输出纯文本字符串,这样甚至不需要在事后去除转义序列.
我有一个字符串:
[33m[TEST][90m [93ma wonderful testorius line[90m ([37mbite me[90m) which ends here.
你看不到它(因为当我 post 它时 Whosebug 会删除它)但是在每个 [xxm
之前都有一个特殊的 Unicode 字符,其中 xx
是一个变量number 和 [
以及 m
是固定的。您可以在此处找到特殊字符:https://gist.githubusercontent.com/mlocati/fdabcaeb8071d5c75a2d51712db24011/raw/b710612d6320df7e146508094e84b92b34c77d48/win10colors.cmd
所以,它是这样的(特殊字符在这里用$显示):
$[33m[TEST]$[90m $[93ma wonderful testorius line$[90m ($[37mbite me$[90m) which ends here.
现在,我想删除此行中的所有 $[xxm
子字符串,因为它仅用于彩色监视器输出,不应保存到日志文件中。
所以预期的结果应该是:
[TEST] a wonderful testorius line (bite me) which ends here.
我尝试使用 RegEx,但我不明白它(可能由于特殊字符和开放的括号,它更加令人困惑)并且我无法在正常的 .Replace ("this","with_that")
操作中使用通配符。
我怎样才能做到这一点?
在这个简单的例子中,以下 -replace
operation will do, but note that this is not sufficient to robustly remove all variations of ANSI / Virtual Terminal escape sequences:
# Sample input.
# Note: `e is used as a placeholder for ESC and replaced with actual ESC chars.
# ([char] 0x1b)
# In PowerShell (Core) 7+, "..." strings directly understand `e as ESC.
$formattedStr = '`e[33m[TEST]`e[90m `e[93ma wonderful testorius line`e[90m (`e[37mbite me`e[90m) which ends here.' -replace '`e', [char] 0x1b
# \x1b is a regex escape sequence that expands to an ESC char.
$formattedStr -replace '\x1b\[\d*m'
一般来说,建议在生成此类用于显示格式的字符串的程序上寻找选项,使它们输出纯文本字符串,这样甚至不需要在事后去除转义序列.