How to replace all occurrences of X between Y?

I'm not sure if this problem has been resolved using regular expressions (in Perl5 syntax), but here is an explanatory example:

smth Y1 test X foo X Y2 bar X Y1 XX Y2 s/?/Z/g smth Y1 test Z foo Z Y2 bar X Y1 ZZ Y2 

Note that Y1 always has a matching Y2 and does not overlap.

+4
source share
3 answers

Here you go:

 $str = 'smth Y1 test X foo X Y2 bar X Y1 XX Y2'; $str =~ s/X(?=((?!Y1).)*Y2)/Z/g; print $str; #smth Y1 test Z foo Z Y2 bar X Y1 ZZ Y2 
+4
source

A bit uncomfortable, but:

 my $string = 'smth Y1 test X foo X Y2 bar X Y1 XX Y2'; $string =~ s/(Y1.*?Y2)/ (my $tmp = "$1") =~ tr!X!Z!; $tmp /ge; print $string; 
+3
source

My interpretive solution (in Perl):

 $sample = 'smth Y1 test X foo X Y2 bar X Y1 XX Y2'; $sample =~ s/(?<=Y1) ((?:(?!Y1|Y2).)+) (?=Y2)/subX($1)/xeg; sub subX { ($str) = @_; $str =~ s/X/Z/g; return $str; } print $sample; 

Output:

smth Y1 test Z foo Z Y2 bar X Y1 ZZ Y2

+1
source

All Articles