perl regex 中的单独反向引用后跟数字文字 [英] Seperate backreference followed by numeric literal in perl regex
问题描述
我发现了这个相关的问题:在 perl 中,替换文本中的反向引用,后跟数字文字但似乎完全不同.我有一个这样的正则表达式
I found this related question : In perl, backreference in replacement text followed by numerical literal but it seems entirely different. I have a regex like this one
s/([^0-9])([xy])/\1 1\2/g
^
whitespace here
但是这个空格出现在替换中.
But that whitespace comes up in the substitution.
如何在不让 perl 混淆对 \11
的反向引用的情况下获取替换字符串中的空格?
How do I not get the whitespace in the substituted string without having perl confuse the backreference to
\11
?
例如.15+x+y
变为 15+1x+1y
.我想得到 15+1x+1y
.
For eg.
15+x+y
changes to 15+ 1x+ 1y
.
I want to get 15+1x+1y
.
推荐答案
\1
是一个正则表达式原子,它匹配第一个捕获捕获的内容.在替换表达式中使用它是没有意义的.你想要 $1
.
\1
is a regex atom that matches what the first capture captured. It makes no sense to use it in a replacement expression. You want $1
.
$ perl -we'$_="abc"; s/(a)/\1/'
\1 better written as $1 at -e line 1.
在字符串文字(包括替换的替换表达式)中,您可以使用卷曲分隔 $var
:${var}
.这意味着您需要以下内容:
In a string literal (including the replacement expression of a substitution), you can delimit $var
using curlies: ${var}
. That means you want the following:
s/([^0-9])([xy])/${1}1$2/g
以下更有效(尽管对 xxx
给出了不同的答案):
The following is more efficient (although gives a different answer for xxx
):
s/[^0-9]\K(?=[xy])/1/g
这篇关于perl regex 中的单独反向引用后跟数字文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!