Logo

Programming-Idioms

History of Idiom 296 > diff from v10 to v11

Edit summary for version 11 by programming-idioms.org:
Admin deletes impl 5464: y and z are string variables, not literal characters

Version 10

2022-02-20, 09:17:32

Version 11

2022-02-20, 19:46:08

Idiom #296 Replace last occurrence of substring

Assign to x2 the value of string x with the last occurrence of y replaced by z.
If y is not contained in x, then x2 has the same value as x.

Idiom #296 Replace last occurrence of substring

Assign to x2 the value of string x with the last occurrence of y replaced by z.
If y is not contained in x, then x2 has the same value as x.

Variables
x2,x,y,z
Variables
x2,x,y,z
Extra Keywords
substring substitute
Extra Keywords
substring substitute
Code
my $x2 = $x;
$x2 =~ s/y([^y]*)$/z$1/;
Comments bubble
Using regex to find the last 'y' in the string and capture anything after it. Then replace the 'y' with 'z' and put the captured info back in ($1).
Doc URL
https://perldoc.perl.org/functions/s
Demo URL
http://codepad.org/LwnULDDE