Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace all occurrences of X between Y's?

I'm not sure if this problem solvable with regular expressions (in Perl5 syntax), but here is self-explanatory example:

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

Consider that Y1 always have a matching Y2 and there is no overlapping.

like image 788
Andrew Avatar asked Feb 24 '23 08:02

Andrew


2 Answers

Here you go:

$str = 'smth Y1 test X foo X Y2 bar X Y1 X X Y2';
$str =~ s/X(?=((?!Y1).)*Y2)/Z/g;
print $str; #smth Y1 test Z foo Z Y2 bar X Y1 Z Z Y2
like image 109
Jacob Eggers Avatar answered Mar 03 '23 06:03

Jacob Eggers


A little awkward, but:

my $string = 'smth Y1 test X foo X Y2 bar X Y1 X X Y2';
$string =~ s/(Y1.*?Y2)/ (my $tmp = "$1") =~ tr!X!Z!; $tmp /ge;
print $string;
like image 45
ysth Avatar answered Mar 03 '23 07:03

ysth