Using regex to add leading zeroes

后端 未结 11 1108
长情又很酷
长情又很酷 2020-12-05 13:07

I would like to add a certain number of leading zeroes (say up to 3) to all numbers of a string. For example:

Input: /2009/5/song 01 of 12

Outpu

11条回答
  •  無奈伤痛
    2020-12-05 13:45

    Here is a Perl solution without callbacks or recursion. It does use the Perl regex extension of execution of code in lieu of the straight substitution (the e switch) but this is very easily extended to other languages that lack that construct.

    #!/usr/bin/perl
    
    while () {
       chomp;
       print "string:\t\t\t$_\n";
    # uncomment if you care about 0000000 case:
    #   s/(^|[^\d])0+([\d])/\1\2/g;
    #   print "now no leading zeros:\t$_\n";    
       s/(^|[^\d]{1,3})([\d]{1,3})($|[^\d]{1,3})/sprintf "%s%04i%s",$1,$i=$2,$3/ge;
       print "up to 3 leading zeros:\t$_\n";
    }
    print "\n";
    
    __DATA__
    /2009/5/song 01 of 12
    /2010/10/song 50 of 99
    /99/0/song 1 of 1000
    1
    01
    001
    0001
    /001/
    "02"
    0000000000
    

    Output:

    string:                /2009/5/song 01 of 12
    up to 3 leading zeros:  /2009/0005/song 0001 of 0012
    string:                /2010/10/song 50 of 99
    up to 3 leading zeros:  /2010/0010/song 0050 of 0099
    string:                /99/0/song 1 of 1000
    up to 3 leading zeros:  /0099/0/song 0001 of 1000
    string:                1
    up to 3 leading zeros:  0001
    string:                01
    up to 3 leading zeros:  0001
    string:                001
    up to 3 leading zeros:  0001
    string:                0001
    up to 3 leading zeros:  0001
    string:                /001/
    up to 3 leading zeros:  /0001/
    string:                "02"
    up to 3 leading zeros:  "0002"
    string:                0000000000
    up to 3 leading zeros:  0000000000
    

提交回复
热议问题