Passing a function to Powershell's (replace) function

前端 未结 2 1973
你的背包
你的背包 2020-11-30 13:39

I want to pass a function call(which returns a string) as a replacement string to Powershell\'s replace function such that each match found is replaced with a different stri

2条回答
  •  爱一瞬间的悲伤
    2020-11-30 14:24

    Perhaps you are looking for Regex.Replace Method (String, MatchEvaluator). In PowerShell a script block can be used as MatchEvaluator. Inside this script block $args[0] is the current match.

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

    Output:

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

提交回复
热议问题