Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 如何在powershell中替换为已计算代码?_Regex_Perl_Powershell - Fatal编程技术网

Regex 如何在powershell中替换为已计算代码?

Regex 如何在powershell中替换为已计算代码?,regex,perl,powershell,Regex,Perl,Powershell,我很难找到一个“本机”powershell-replace调用,该调用将使用基于匹配的内容替换匹配。例如,在perl中,它是这样的: my%definedVars=(ab=>“你好”,cd=>“那里”); my$str=q“$(ab)$(cd)”; $str=~s/\$\([^)]+)\/$definedVars{$1}/ge; 打印“$str\n”; 我在想,在powershell中,应该是这样的: $definedVars=@{ab='hello';cd='there'} “$(ab)$(

我很难找到一个“本机”powershell-replace调用,该调用将使用基于匹配的内容替换匹配。例如,在perl中,它是这样的:

my%definedVars=(ab=>“你好”,cd=>“那里”);
my$str=q“$(ab)$(cd)”;
$str=~s/\$\([^)]+)\/$definedVars{$1}/ge;
打印“$str\n”;
我在想,在powershell中,应该是这样的:

$definedVars=@{ab='hello';cd='there'}
“$(ab)$(cd)”-替换“\$\([^)]+)\”,{$definedVars[$1]}
我环顾四周,认为
-replace
开关没有延迟求值器,因此我不得不使用.NET
replace
函数,但我不完全确定它是如何工作的。我想应该是这样的:

$definedVars=@{ab='hello';cd='there'}
[正则表达式]:替换(“$(ab)$(cd)”,
"\$\(([^)]+)\)",
{$definedVars[$\.Groups[1].Value]})

文档很少,所以如果您也能说明您从哪里获得信息,那就太好了。

看起来这只是一个语法问题。我必须指定参数并使用它<代码>$\u未定义为特殊的默认参数。所以它是这样的:

$definedVars=@{ab='hello';cd='there'}
[正则表达式]:替换(“$(ab)$(cd)”,
"\$\(([^)]+)\)",
{param($m);$definedVars[$m.Groups[1].Value]})
编辑 正如mjolinor指出的,我可以使用
$args
数组来代替定义参数,如下所示:

$definedVars=@{ab='hello';cd='there'}
[正则表达式]:替换(“$(ab)$(cd)”,
"\$\(([^)]+)\)",
{$definedVars[$args[0]。组[1]。值]})

如果我只引用该参数一次,这会稍微好一点,但是如果委托变得更复杂,那么最好使用
param
来指定参数。

这是正确的;您必须为脚本块定义一个参数,并使用它来接收每个匹配项。我从中获得了语法。您不必定义参数。您可以使用$args->[regex]::replace(“$(ab)$(cd)”,“\$([^)]+),{$definedVars[$args[0].Groups[1].Value]})如果本机的
-replace
有一个计算语法就好了。@mjolinor,我以前试过
$args
,但无法使用它。谢谢你的提醒。