我正在尝试替换 Powershell 中的部分字符串。但是,替换字符串不是硬编码的,它是从一个函数计算出来的:
$text = "the image is -12345-"
$text = $text -replace "-(\d*)-", 'This is the image: $1'
Write-Host $text
这给了我正确的结果:
“这是图像:12345”
现在,我想包含 base64 编码的图像。我可以从 id 读取图像。我希望以下内容会起作用,但事实并非如此:
function Get-Base64($path)
{
[convert]::ToBase64String((get-content $path -encoding byte))
}
$text -replace "-(\d*)-", "This is the image: $(Get-Base64 '$1')"
它不起作用的原因是因为它首先通过
$1
(字符串,而不是 $1
的值)到函数,执行它,然后它才进行替换。我想做的是最佳答案
您可以使用静态 Replace
来自 [regex]
的方法类(class):
[regex]::Replace($text,'-(\d*)-',{param($match) "This is the image: $(Get-Base64 $match.Groups[1].Value)"})
或者,您可以定义
regex
对象并使用 Replace
该对象的方法:$re = [regex]'-(\d*)-'
$re.Replace($text, {param($match) "This is the image: $(Get-Base64 $match.Groups[1].Value)"})
为了更好的可读性,您可以在单独的变量中定义回调函数(脚本 block )并在替换中使用它:
$callback = {
param($match)
'This is the image: ' + (Get-Base64 $match.Groups[1].Value)
}
$re = [regex]'-(\d*)-'
$re.Replace($text, $callback)
关于regex - 在 Powershell 中使用函数替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52012425/