【问题标题】:Passing a function to Powershell's (replace) function将函数传递给 Powershell 的(替换)函数
【发布时间】:2011-12-31 01:46:59
【问题描述】:

我想将一个函数调用(它返回一个字符串)作为替换字符串传递给 Powershell 的替换函数,以便将找到的每个匹配项替换为不同的字符串。

有点像 -

$global_counter = 0
Function callback()
{
    $global_counter += 1   
    return "string" + $global_counter
}

$mystring -replace "match", callback()

Python 通过 're' 模块的 'sub' 函数实现这一点,该函数接受回调函数作为输入。寻找类似的东西

【问题讨论】:

    标签: powershell replace


    【解决方案1】:

    PowerShell 不(还没有?)支持将脚本块传递给 -replace 运算符。这里唯一的选择是直接使用[Regex]::Replace

    [Regex]::Replace($mystring, 'match', {callback})
    

    【讨论】:

      【解决方案2】:

      也许您正在寻找Regex.Replace Method (String, MatchEvaluator)。在 PowerShell 中,脚本块可以用作 MatchEvaluator。在这个脚本块内$args[0] 是当前匹配。

      $global_counter = 0
      $callback = {
          $global_counter += 1
          "string-$($args[0])-" + $global_counter
      }
      
      $re = [regex]"match"
      $re.Replace('zzz match match xxx', $callback)
      

      输出:

      zzz string-match-1 string-match-2 xxx
      

      【讨论】:

        猜你喜欢
        • 2023-03-26
        • 2022-10-07
        • 2016-03-30
        • 1970-01-01
        • 2015-07-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多