我发现了这个相关问题:In perl, backreference in replacement text followed by numerical literal
但似乎完全不同。
我有一个这样的正则表达式
s/([^0-9])([xy])/\1 1\2/g
^
whitespace here
但是替换中出现了空白。
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
。
最佳答案
\1
是一个正则表达式原子,与第一个捕获的内容匹配。在替换表达式中使用它是没有意义的。您需要$1
。
$ perl -we'$_="abc"; s/(a)/\1/'
\1 better written as $1 at -e line 1.
在字符串文字(包括替换的替换表达式)中,可以使用curlies来分隔
$var
:${var}
。这意味着您需要以下内容:s/([^0-9])([xy])/${1}1$2/g
以下代码效率更高(尽管
xxx
给出了不同的答案):s/[^0-9]\K(?=[xy])/1/g
关于regex - 在Perl正则表达式中,单独的反向引用后跟数字文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18721037/