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 string.
我想将函数调用(返回一个字符串)作为替换字符串传递给Powershell的替换函数,以便找到的每个匹配项都替换为不同的字符串。
Something like -
就像是 -
$global_counter = 0
Function callback()
{
$global_counter += 1
return "string" + $global_counter
}
$mystring -replace "match", callback()
Python allows this through 're' module's 'sub' function which accepts a callback function as input. Looking for something similar
Python允许通过're'模块的'sub'函数接受回调函数作为输入。寻找类似的东西
2 个解决方案
#1
17
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.
也许您正在寻找Regex.Replace方法(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)
Output:
输出:
zzz string-match-1 string-match-2 xxx
#2
10
PowerShell does not (yet?) have support for passing a script block to the -replace
operator. The only option here is to use [Regex]::Replace
directly:
PowerShell(但是?)不支持将脚本块传递给-replace运算符。这里唯一的选择是直接使用[Regex] :: Replace:
[Regex]::Replace($mystring, 'match', {callback})
#1
17
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.
也许您正在寻找Regex.Replace方法(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)
Output:
输出:
zzz string-match-1 string-match-2 xxx
#2
10
PowerShell does not (yet?) have support for passing a script block to the -replace
operator. The only option here is to use [Regex]::Replace
directly:
PowerShell(但是?)不支持将脚本块传递给-replace运算符。这里唯一的选择是直接使用[Regex] :: Replace:
[Regex]::Replace($mystring, 'match', {callback})