我正在尝试替换 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
) 到函数中,执行它,然后才进行替换。我想做的是
- 查找模式的出现次数
- 用模式替换每个出现的地方
- 对于每次替换:
- 将捕获组传递给函数
- 使用capture group的值获取base64图像
- 将 Base64 图像注入替换图像
您可以使用静态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)"})
为了更好的可读性,您可以在单独的变量中定义回调函数(脚本块)并在替换中使用它:
$callback = {
param($match)
'This is the image: ' + (Get-Base64 $match.Groups[1].Value)
}
$re = [regex]'-(\d*)-'
$re.Replace($text, $callback)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)