Powershell 正则表达式组替换 [英] Powershell regex group replacing

查看:125
本文介绍了Powershell 正则表达式组替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to replace some text in every script file in folder, and I'm trying to use this PS code:

$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 }

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

But I have no idea how to keep first part of expression, and just replace the second one. Any idea how can I do this? Thanks.

推荐答案

不确定为表名称提供的 regex 是否正确,但无论如何您可以使用变量 $1$2 等,并遵循语法:'Doe, John' -ireplace '(\w+), (\w+)', '$2 $1'

Not sure that provided regex for tables names is correct, but anyway you could replace with captures using variables $1, $2 and so on, and following syntax: 'Doe, John' -ireplace '(\w+), (\w+)', '$2 $1'

请注意,替换模式需要在单引号中 ('') 或将替换组说明符的 $ 符号转义 ("`$2 `$1").

Note that the replacement pattern either needs to be in single quotes ('') or have the $ signs of the replacement group specifiers escaped ("`$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
}

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

If you need to reference other variables in your replacement expression (as you may), you can use a double-quoted string and escape the capture dollars with a backtick

     { $_-replace $pattern, "`$1 replacement text with $somePoshVariable" } | 

这篇关于Powershell 正则表达式组替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆