用更 PowerShell 惯用的解决方案 和一些背景信息来补充 Shawn Tabrizi's helpful answer:
PowerShell 通过自己的 -replace operator 展示 .NET System.Text.RegularExpressions.Regex.Replace() 方法([regex]::Replace(),来自 PowerShell)的功能。
最简洁的解决方案(但请参阅下面的潜在陷阱):
# Note the escaped "$" ("`$")
"<'sample text'><'sample text 2'>" -replace '<(.*?)>', "`$1`n"
输出:
'sample text'
'sample text 2'
-
$1 是 numbered capture-group substitution,指的是正则表达式 ((...)) 中的第一个(也是唯一一个)捕获组捕获的内容,即 < 和 > 之间的字符串(.*? 是non-greedy 表达式匹配任何字符运行,但在找到下一个构造(在本例中为 >)时停止)。
-
但是,在 双 引号内的字符串 ("..."),也称为 expandable string,$1 将被解释为 PowerShell 变量引用,因此 $ 字符必须转义才能保留,使用反引号 (`),PowerShell 的一般转义字符:"`$1"
-
相反,如果您希望 .NET API 不解释替换字符串中的 $ 字符,请使用 $$($$ 在 @ 987654347@ 或 "`$`$" 内 "...") - 但请注意,在 regex 操作数内,$ 必须逐字转义为 \$。
-
"`n" 是一个 PowerShell 转义序列,可在可扩展字符串中使用(仅限) - 请参阅概念性 about_Special_Characters 帮助主题。
警告:
这就是肖恩在回答中所做的;转换为-replace 操作:
# Note the expression used to build the substitution string
# from a verbatim ('...') and an interpolated ("...") part.
"<'sample text'><'sample text 2'>" -replace '<(.*?)>', ('${1}' + "`n")
另一个选项,使用-f,format operator:
"<'sample text'><'sample text 2'>" -replace '<(.*?)>', ("{0}`n" -f '${1}')
注意使用${1} 而不仅仅是$1:在{...} 中包含引用的捕获组的编号/名称消除歧义从后面的字符,这避免了另一个陷阱,如以下示例所示(顺便说一下,PowerShell 自己的变量引用可以用相同的方式消除歧义):
# FAILS and results in 'f$142', because the .NET API sees
# '$142' as the substitution string, and there is no 142nd capture group.
$suffix = '42'; 'foo' -replace '(oo)', ('$1' + $suffix)
# OK, with disambiguation via {...} -> 'foo42'
$suffix = '42'; 'foo' -replace '(oo)', ('${1}' + $suffix)