开发者

What regular expression do I use for replacing numbers with leading zeros?

I have a bunch of strings like this:

my $string1 = "xg0000";
my $string2 = "fx0015";

What do I do to increase the 开发者_如何学Gonumber in the string by 1 but also maintain the leading zeros to keep the length of the string the same.

I tried this:

$string =~ s/(\d+)/0 x length(int($1)) . ($1+1)/e;

It doesn't seem to work on all numbers. Is regex what I'm supposet to use to do this or is there a better way?


How about a little perl magic? The ++ operator will work even on strings, and 0000 will magically turn into 0001.

Now, we can't modify $1 since it is readonly, but we can use an intermediate variable.

use strict;
use warnings;
my $string = "xg0000"; 
$string =~ s/(\d+)/my $x=$1; ++$x/e; 

Update:

I didn't think of this before, but it actually works without a regex:

C:\perl>perl -we "$str = 'xg0000'; print ++$str;"
xg0001

Still does not solve the problem DavidO pointed out, with 9999. You would have to decide what to do with those numbers. Perl has a rather interesting solution for it:

C:\perl>perl -we "$str = 'xg9999'; print ++$str;"
xh0000


You can do it with sprintf too, and use the length you compute from the number of digits that you capture:

use strict;
use warnings;

my $string = "xg00000";

foreach ( 0 .. 9 ) {
    $string =~ s/([0-9]+)\z/
        my $l = length $1;
        sprintf "%0${l}d", $1 + 1;
        /e; 
    print "$string\n";
    }


This is a really bad task to solve with a regexp. Increasing a number can change an unlimited number of digits, and can in fact also change the number of non-zero digits! Unless you have sworn an oath to use only regexes for a year, use regex to extract the number and then sprintf "%06d" $x+1 to regenerate the new number with the desired width.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜