Reputation: 18898
I want to suffix a group match with a digit in a rexeg replace expression. How do I separate the match variable from the actal digit?
If I want
hello 55 friends -> hello 551 friend
i am 29 happy -> i am 291 happy
I tried with
s/([0-9]+)/$11/g;
But if I put a 1
directly after $1
, perl interprets it as $11
(rightfully so). In bash, I could have written ${1}1
, but this doesn't seem to work in perl.
EDIT: Turns out that @toolic was right, s/([0-9]+)/${1}1/g; does work, I had an escaping issue with my shell. If you post that answer as a proper answer I'll accept it! Thanks
Upvotes: 2
Views: 149
Reputation: 39394
As stated in the comments, the optional curly braces for backreferences (e.g. ${1}
instead of $1
) does work in perl.
Upvotes: 1
Reputation: 2691
You can use regex : (\d+)
and replace capture group with suffix 1
Example :
<?php
$string = 'hello 55 friends i am 29 happ';
$pattern = '/(\d+)/';
$replacement = '${1}1';
echo preg_replace($pattern, $replacement, $string);
?>
Upvotes: 0