Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seperate backreference followed by numeric literal in perl regex

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.

like image 937
udiboy1209 Avatar asked Sep 10 '13 14:09

udiboy1209


2 Answers

\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
like image 105
ikegami Avatar answered Sep 28 '22 19:09

ikegami


Just put braces around the number:

s/([^0-9])([xy])/${1}1${2}/g
like image 28
Toto Avatar answered Sep 28 '22 20:09

Toto