Perl Regexp only works once

I need to process the string with regexp and change x-> y if that is the number around.

Row : 2x2x2 2x 2x2x 2x2x2x2x2

Regexp : s/([0-9])x([0-9])/$1y$2/g

 my $string = "2x2x2 2x 2x2x 2x2x2x2x2"; $string =~ s/([0-9])x([0-9])/$1y$2/g; print "$string\n"; 

I expect: 2y2y2 xx 2x 2y2x 2y2y2y2y2

But the result: 2y2x2 2x 2y2x 2y2x2y2x2 (not all 2x2 changed)

What should I do?

+6
source share
2 answers

Try the following regex:

 s/(?<=\d)x(?=\d)/y/g 
+8
source

To be explicit: the reason "2x2x2" turns into "2y2x2" is because your expression first matches "2x2" , replaces it with "2y2" , and then resumes the search after this match is found. The next bit is "x2" , which does not match your pattern.

The reason for @xdazz's solution is that look-around statements do not actually consume string characters. The part matched on the line is "x" when it is preceded and followed by numbers.

By the way, changing @xdazz from [0-9] to \d does not change very much, but it is slightly different: \d will also correspond to other Unicode characters, which are considered digits, while [0-9] only matches the exact 10 characters in given range.

+2
source

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


All Articles