regex - 在 Powershell 中使用函数替换

标签 regex powershell

我正在尝试替换 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 的值)到函数,执行它,然后它才进行替换。我想做的是
  • 查找模式的出现
  • 用模式
  • 替换每个出现
  • 对于每次替换:
  • 将捕获组传递给函数
  • 使用捕获组的值获取base64图像
  • 将base64图像注入(inject)替换
  • 最佳答案

    您可以使用静态 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/

    相关文章:

    powershell - 在 shell 中使用制表符完成建议的命令

    xml - Powershell 空 XML 元素格式化为一行

    powershell - 如何在 powershell 中正确创建和修改元组的哈希集?

    c# - 正则表达式 - 在 C# 中的括号和字母数字字符之间插入空格

    php - mysql 正则表达式构建

    javascript - 正则表达式捕获 utf-8 行分隔符

    powershell - 更改 Path 环境变量中的值

    azure - 用于从 Azure 文件共享还原 Azure SQL 数据库的 PowerShell 脚本

    c# - C#中用于文件名验证的正则表达式

    javascript - 匹配阿姆斯特丹邮政编码的正则表达式