Swa*_*nil 11 powershell replace
我想将函数调用(返回一个字符串)作为替换字符串传递给Powershell的替换函数,以便找到的每个匹配项都替换为不同的字符串.
就像是 -
$global_counter = 0
Function callback()
{
$global_counter += 1
return "string" + $global_counter
}
$mystring -replace "match", callback()
Run Code Online (Sandbox Code Playgroud)
Python允许通过're'模块的'sub'函数接受回调函数作为输入.寻找类似的东西
Rom*_*min 18
也许您正在寻找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)
Run Code Online (Sandbox Code Playgroud)
输出:
zzz string-match-1 string-match-2 xxx
Run Code Online (Sandbox Code Playgroud)
Joe*_*oey 10
PowerShell(但是?)不支持将脚本块传递给-replace操作员.这里唯一的选择是[Regex]::Replace直接使用:
[Regex]::Replace($mystring, 'match', {callback})
Run Code Online (Sandbox Code Playgroud)