在 perl 中,替换文本中的反向引用后跟数字文字 [英] In perl, backreference in replacement text followed by numerical literal
问题描述
我在替换文本中后跟文字时遇到反向引用问题.我尝试了以下方法:
I'm having trouble with a backreference in my replacement text that is followed by a literal. I have tried the following:
perl -0pi -e "s/(<tag1>foo<\/tag1>\n\s*<tag2>)[^\n]*(<\/tag2>)/\1${varWithLeadingNumber}\2/" file.xml
perl -0pi -e "s/(<tag1>foo<\/tag1>\n\s*<tag2>)[^\n]*(<\/tag2>)/\g{1}${varWithLeadingNumber}\g{2}/" file.xml
第一个当然会导致问题,因为 ${varWithLeadingNumber} 以数字开头,但我认为上面第二次尝试中的 \g{1}
构造应该可以解决这个问题.我使用的是 perl 5.12.4.
The first of course causes problems because ${varWithLeadingNumber} begins with a number, but I thought the \g{1}
construct in my second attempt above was supposed to solve this problem. I'm using perl 5.12.4.
推荐答案
在替换表达式中使用\1
、\2
等是错误的.\1
是一个正则表达式模式,表示匹配第一个捕获匹配的内容",这在替换表达式中没有意义.不应在正则表达式之外使用正则表达式模式!$1
、$2
等是你应该在那里使用的.
Using \1
, \2
, etc in the replacement expression is wrong. \1
is a regular expression pattern that means "match what the first capture matched" which makes no sense in a replacement expression. Regular expression patterns should not be used outside of regular expressions! $1
, $2
, etc is what you should be using there.
修复\1
后,你有
perl ... -e'... s/.../...$1$varWithLeadingNumber.../ ...'
也就是说,我认为 varWithLeadingNumber
应该是一个 shell 变量?如果它是 Perl 变量,您应该不会有任何问题.如果您让 shell 对 varWithLeadingNumber
进行插值,则可以使用
That said, I think varWithLeadingNumber
is supposed to be a shell variable? You shouldn't have any problems if it's a Perl variable. If you're having the shell interpolate varWithLeadingNumber
, the problem can be fixed using
perl ... -e"... s/.../...\${1}${varWithLeadingNumber}.../ ..."
请注意,如果 $varWithLeadingNumber 包含$"、@"、\"或/",则会出现问题,因此您可能需要使用命令行参数而不是插值.
Note that you will have problems if $varWithLeadingNumber contains "$", "@", "\" or "/", so you might want to use a command line argument instead of interpolation.
perl ... -pe'
BEGIN { $val = shift; }
... s/.../...$1$val.../ ...
' "${varWithLeadingNumber}"
您也可以使用环境变量.
You could also use an environment variable.
export varWithLeadingNumber
perl ... -pe's/.../...$1$ENV{varWithLeadingNumber}.../'
或
varWithLeadingNumber=varWithLeadingNumber \
perl ... -pe's/.../...$1$ENV{varWithLeadingNumber}.../'
<小时>
如果你有 \1
s/...\1.../.../
您可以通过多种方式避免该问题,包括
you can avoid the problem a number of ways including
s/...(?:\1).../.../
这篇关于在 perl 中,替换文本中的反向引用后跟数字文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!