我正在文件中搜索以下正则表达式模式 “[a-zA-Z0-9]+[^”]+[a-zA-Z0-9]+” 该模式包含所有文本,包括空格。我正在尝试将文件中与上述模式匹配的所有条目的空格(\s)替换为下划线(_)
(Get-Content .\temp.log -raw) -replace '("[a-zA-Z0-9]+[^"]+[a-zA-Z0-9]+")', {$($1.replace(' ','_'))}
让我知道我在这里缺少什么。
当您使用 脚本块 (
{ ... }
) 作为替换操作数时(仅在 PowerShell (Core) 7 中受支持),您必须通过 automatic 引用手头的匹配$_
变量:
(Get-Content .\temp.log -raw) -replace '("[a-zA-Z0-9]+[^"]+[a-zA-Z0-9]+")',
{ $_.Groups[1].Value -replace ' ', '_' }