【问题标题】:How to replace with evaluated code in powershell?如何用powershell中的评估代码替换?
【发布时间】:2015-11-13 14:50:25
【问题描述】:

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

my %definedVars = ( ab => "hello", cd => "there" );
my $str = q"$(ab) $(cd)";
$str =~ s/\$\(([^)]+)\)/$definedVars{$1}/ge;
print "$str\n";

我在想,在 powershell 中,它会是这样的:

$definedVars = @{ ab = 'hello'; cd = 'there' }
'$(ab) $(cd)' -replace "\$\(([^)]+)\)", { $definedVars[$1] }

我环顾四周,我认为 -replace 开关没有延迟评估器,所以我必须使用 .NET replace 函数,但我不完全确定它是如何工作的.我想应该是这样的:

$definedVars = @{ ab = 'hello'; cd = 'there' }
[regex]::replace('$(ab) $(cd)',
   "\$\(([^)]+)\)",
   { $definedVars[$_.Groups[1].Value] } )

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

【问题讨论】:

    标签: regex perl powershell


    【解决方案1】:

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

    $definedVars = @{ ab = 'hello'; cd = 'there' }
    [regex]::replace('$(ab) $(cd)',
       "\$\(([^)]+)\)",
       { param($m); $definedVars[$m.Groups[1].Value] } )
    

    编辑

    正如 mjolinor 指出的那样,我可以使用 $args 数组代替定义参数,而不是定义参数,如下所示:

    $definedVars = @{ ab = 'hello'; cd = 'there' }
    [regex]::replace('$(ab) $(cd)',
       "\$\(([^)]+)\)",
       { $definedVars[$args[0].Groups[1].Value] } )
    

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

    【讨论】:

    • 这是正确的;您必须为脚本块定义一个参数并使用它来接收每个匹配项。
    • 您不必定义参数。您可以使用 $args -> [regex]::replace('$(ab) $(cd)', "\$(([^)]+))", { $definedVars[$args[0].Groups [1].值] })
    • 如果原生 -replace 有评估语法就好了。
    • @mjolinor,我之前尝试过$args,但无法正常工作。谢谢提醒。
    猜你喜欢
    • 1970-01-01
    • 2013-02-01
    • 2011-01-25
    • 1970-01-01
    • 1970-01-01
    • 2015-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多