开发者

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


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; 


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.


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


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜