将函数传递给 Powershell 的(替换)函数 [英] Passing a function to Powershell's (replace) function

查看:50
本文介绍了将函数传递给 Powershell 的(替换)函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

类似 -

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

$mystring -replace "match", callback()

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

Python allows this through 're' module's 'sub' function which accepts a callback function as input. Looking for something similar

推荐答案

也许您正在寻找 正则表达式.替换方法(字符串,MatchEvaluator).在 PowerShell 中,脚本块可以用作 MatchEvaluator.在此脚本块中 $args[0] 是当前匹配项.

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)

输出:

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

这篇关于将函数传递给 Powershell 的(替换)函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆