Powershell正则表达式组取代

hmn*_*nzr 12 regex powershell replace

我想替换文件夹中每个脚本文件中的一些文本,我正在尝试使用此PS代码:

$pattern = '(FROM [a-zA-Z0-9_.]{1,100})(?<replacement_place>[a-zA-Z0-9_.]{1,7})'
Get-ChildItem -Path 'D:\Scripts' -Recurse -Include *.sql | ForEach-Object { (Get-Content $_.fullname) -replace $pattern, 'replace text' | Set-Content $_.fullname }
Run Code Online (Sandbox Code Playgroud)

但我不知道如何保留表达式的第一部分,而只是替换第二部分.知道我该怎么办?谢谢.

Aki*_*kim 27

不确定为表名提供的正则表达式是否正确,但无论如何,您可以使用变量替换捕获$1,$2依此类推,并遵循以下语法:'Doe, John' -ireplace '(\w+), (\w+)', '$2 $1'

请注意,替换模式需要使用单引号('')或具有$替换组说明符的符号("`$2 `$1").

# may better replace with     $pattern = '(FROM) (?<replacement_place>[a-zA-Z0-9_.]{1,7})'
$pattern = '(FROM [a-zA-Z0-9_.]{1,100})(?<replacement_place>[a-zA-Z0-9_.]{1,7})'

Get-ChildItem -Path 'D:\Scripts' -Recurse -Include *.sql | % `
{
   (Get-Content $_.fullname) | % `
     { $_-replace $pattern, '$1 replace text' } | 
     Set-Content $_.fullname -Force
}
Run Code Online (Sandbox Code Playgroud)

如果你需要在替换表达式中引用其他变量(如你所愿),你可以使用双引号字符串并用反引号转义捕获元数

     { $_-replace $pattern, "`$1 replacement text with $somePoshVariable" } | 
Run Code Online (Sandbox Code Playgroud)

  • 在你的情况下,@ user3700562围绕#花括号中的#$ {1} $ version` (7认同)