在替换期间强制立即评估反向引用 [英] Force immediate evaluation of backreference during replace
问题描述
我遇到了一个错误,我将字符串连接在一起以获得我想要替换的字段.
I am running into an error where I am concatenating strings together to obtain the field I want replaced.
以下是我的脚本正在执行的操作的示例:
Below is an example of what my script is doing:
$TEXTTOREPLACEWITH= '6Q'
(Get-Content testfile.html) | ForEach-Object { $_ -replace '(.*)\$\(STRINGTOREPLACE\)(.*)', ('$1' +$TEXTTOREPLACEWITH+'$2')
如果我对一个输入如下的文件运行这个:
If I ran this against a file that had a line input as follows:
abc$(STRINGTOREPLACE)xyz
我希望得到以下输出:
abc6Qxyz
相反,当我运行此脚本时,输出如下所示:
INSTEAD, When I run this script the output looks as follows:
$16Qxyz
我假设这是因为在字符串连接完成之前不能解析反向引用.在 PowerShell 中是否有任何方法可以立即解决这些反向引用并避免我看到的输出?
I'm assuming this is due to the fact that back-references must not be resolved until string concatenation is complete. Is there any way in PowerShell to go ahead and resolve these back-references immediately and avoid the output that I am seeing?
推荐答案
1st,漏点,答案已替换...
当连接 '$1'
和 '6Q'
时(在传递给正则表达式引擎之前)你得到 $16Q
并且没有要替换的第 16 个 捕获.
When concatenate '$1'
and '6Q'
(before being passed to the regex engine) you get $16Q
and there is no 16th capture to replace.
为避免这种情况,请在匹配中使用命名组 ((?
) 并在替换字符串中使用 ${name}
.
To avoid this, use named groups in the match ((?<name>)
) and ${name}
in the replacement string.
请参阅文档,并注意:
如果 number 未指定在正则表达式模式中定义的有效捕获组,则 $number
将被解释为用于替换每个匹配项的文字字符序列.
If number does not specify a valid capturing group defined in the regular expression pattern,
$number
is interpreted as a literal character sequence that is used to replace each match.
这篇关于在替换期间强制立即评估反向引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!