benzebuth
benzebuth

Reputation: 695

substition regex, with capture

maybe this is a stupid question but :
i run perl 5.8.8 and i need to replace any underscore preceded by a number, with "0".

running :

 $var =~s /(\d)_/$10/g; 
obviously does not work as $10 is interpreted as... well... $10, not "$1 followed by 0"

moreover, as runing perl5.8, i can't do

$var=~s/(?<n1>\d)\_/$+{n1}0/g;

any idea ?
thanks in advance

Upvotes: 1

Views: 119

Answers (4)

FMc
FMc

Reputation: 42411

Just like in various Unix shells, you can enclose the variable name in braces for disambiguation.

$var =~s /(\d)_/${1}0/g;

Or you can use a look-behind to prevent the digit from being part of the match:

$var =~s /(?<=\d)_/0/g; 

Upvotes: 11

Robert Wohlfarth
Robert Wohlfarth

Reputation: 1771

This would also be a good place for a zero width look-behind assertion:

$var =~ s/(?<=\d)_/0/g;

It looks for a digit without actually slurping the digit into the matched text.

Upvotes: 2

jpalecek
jpalecek

Reputation: 47762

Another possibilities are (not sure if applicable to perl 5.8.8)

s/\d\K_/0/
s/(?<=\d)_/0/

Upvotes: 0

Mark Thomas
Mark Thomas

Reputation: 37507

$var =~s/(\d)_/${1}0/g;

Upvotes: 0

Related Questions