具有命名组的替换字符串中的Powershell变量

时间:2021-04-07 00:35:27

The following Powershell replace operation with named groups s1 and s2 in regex (just for illustration, not a correct syntax) works fine :

以下Powershell替换操作与正则表达式中的命名组s1和s2(仅用于说明,而不是正确的语法)工作正常:

$s -Replace "(?<s1>....)(?<s2>...)" '${s2}xxx${s1}'

My question is : how to replace with a variable $x instead of the literal xxx, that is, something like :

我的问题是:如何替换变量$ x而不是文字xxx,即:

$s -Replace "(?<s1>....)(?<s2>...) '${s2}$x${s1}'

That doesn't work as Powershell doesn't replace variable in single quoted string but the named group resolution doesn't work anymore if replacement string is put in double quotes like this "${s2}$x${s1}".

这不起作用,因为Powershell不替换单引号字符串中的变量,但如果替换字符串放在双引号中,如“$ {s2} $ x $ {s1}”,则命名组解析不再起作用。

1 个解决方案

#1


3  

@PetSerAl comment is correct, here is code to test it:

@PetSerAl评论是正确的,这里是测试它的代码:

$sep = ","
"AAA BBB" -Replace '(?<A>\w+)\s+(?<B>\w+)',"`${A}$sep`${B}"

Output: AAA,BBB

Explanation:

Powershell will evaluate the double quoted string, escaping the $ sign with a back tick will ensure these are not evaluated and a valid string is provided for the -Replace operator.

Powershell将评估双引号字符串,使用后退标记转义$符号将确保不评估这些字符串并为-Replace运算符提供有效字符串。

or via Get-Help about_escape & Get-Help about_comparison_operators

或通过Get-Help about_escape和Get-Help about_comparison_operators

#1


3  

@PetSerAl comment is correct, here is code to test it:

@PetSerAl评论是正确的,这里是测试它的代码:

$sep = ","
"AAA BBB" -Replace '(?<A>\w+)\s+(?<B>\w+)',"`${A}$sep`${B}"

Output: AAA,BBB

Explanation:

Powershell will evaluate the double quoted string, escaping the $ sign with a back tick will ensure these are not evaluated and a valid string is provided for the -Replace operator.

Powershell将评估双引号字符串,使用后退标记转义$符号将确保不评估这些字符串并为-Replace运算符提供有效字符串。

or via Get-Help about_escape & Get-Help about_comparison_operators

或通过Get-Help about_escape和Get-Help about_comparison_operators