使用 Powershell 中的函数替换 [英] Use a function in Powershell replace
问题描述
我正在尝试替换 Powershell 中的部分字符串.但是,替换字符串不是硬编码的,它是从函数计算出来的:
I'm trying to replace part of a string in Powershell. However, the replacement string is not hardcoded, it's calculated from a function:
$text = "the image is -12345-"
$text = $text -replace "-(\d*)-", 'This is the image: $1'
Write-Host $text
这给了我正确的结果:这是图像:12345"
This gives me the correct result: "This is the image: 12345"
现在,我想包含 base64 编码的图像.我可以从 id 中读取图像.我希望以下内容有效,但没有:
Now, I want to include the base64 encoded image. I can read the image from the id. I was hoping the following would work, but it doesn't:
function Get-Base64($path)
{
[convert]::ToBase64String((get-content $path -encoding byte))
}
$text -replace "-(\d*)-", "This is the image: $(Get-Base64 '$1')"
它不工作的原因是因为它首先将 $1
(字符串,而不是 $1
的值)传递给函数,执行它并且只执行然后它做替换.我想做的是
The reason that it doesn't work, is because it first passes $1
(the string, not the value of $1
) to the function, executes it and only then does it do the replace. What I want to do is
- 找出模式的出现
- 用模式替换每次出现
- 对于每次替换:
- 将捕获组传递给函数
- 使用捕获组的值获取base64图像
- 将 base64 图像注入到替换中
推荐答案
您可以使用静态<[regex]
类中的 code>Replace 方法:
You can use the static Replace
method from the [regex]
class:
[regex]::Replace($text,'-(\d*)-',{param($match) "This is the image: $(Get-Base64 $match.Groups[1].Value)"})
或者,您可以定义一个 regex
对象并使用该对象的 Replace
方法:
Alternatively you can define a regex
object and use the Replace
method of that object:
$re = [regex]'-(\d*)-'
$re.Replace($text, {param($match) "This is the image: $(Get-Base64 $match.Groups[1].Value)"})
为了更好的可读性,您可以在单独的变量中定义回调函数(脚本块)并在替换中使用它:
For better readability you could define the callback function (the scriptblock) in a separate variable and use that in the replacement:
$callback = {
param($match)
'This is the image: ' + (Get-Base64 $match.Groups[1].Value)
}
$re = [regex]'-(\d*)-'
$re.Replace($text, $callback)
这篇关于使用 Powershell 中的函数替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!