Seperate backreference followed by numeric literal in perl regex

馋奶兔 提交于 2020-12-20 08:00:50

问题


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.

How do I not get the whitespace in the substituted string without having perl confuse the backreference to \11?

For eg. 15+x+y changes to 15+ 1x+ 1y. I want to get 15+1x+1y.


回答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.

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

The following is more efficient (although gives a different answer for xxx):

s/[^0-9]\K(?=[xy])/1/g



回答2:


Just put braces around the number:

s/([^0-9])([xy])/${1}1${2}/g


来源:https://stackoverflow.com/questions/18721037/seperate-backreference-followed-by-numeric-literal-in-perl-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!