Separate trackback followed by a numeric literal in perl regex

I found this related question: In perl, the backreference in the replacement text is followed by a numeric literal but it seems completely different. I have a regex like this

s/([^0-9])([xy])/\1 1\2/g ^ whitespace here 

But this gap appears in the wildcard.

How can I not get a space in the replaced string without having perl, confuse backreference with \11 ?

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

+6
source share
2 answers

\1 is a regular expression atom that matches the capture of the first capture. 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 wildcard expression), you can delimit $var with curlies: ${var} . This means that you want the following:

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

Below is a more efficient one (although it gives a different answer for xxx ):

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

Just put the braces around the number:

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

Source: https://habr.com/ru/post/953570/


All Articles