Using regex to add leading zeroes

后端 未结 11 1123
长情又很酷
长情又很酷 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

    Combined in Xcode:

    targetName=[NSString stringWithFormat:@"%05d",number];
    

    Gives 00123 for number 123

    0 讨论(0)
  • 2020-12-05 13:47

    Another approach:

    >>> x
    '/2009/5/song 01 of 12'
    >>> ''.join([i.isdigit() and i.zfill(4) or i for i in re.split("(?<!\d)(\d+)(?!\d)",x)])
    '/2009/0005/song 0001 of 0012'
    >>>
    

    Or:

    >>> x
    '/2009/5/song 01 of 12'
    >>> r=re.split("(?<!\d)(\d+)(?!\d)",x)
    >>> ''.join(a+b.zfill(4) for a,b in zip(r[::2],r[1::2]))
    '/2009/0005/song 0001 of 0012'
    
    0 讨论(0)
  • 2020-12-05 13:51

    Use something that supports a callback so you can process the match:

    >>> r=re.compile(r'(?:^|(?<=[^0-9]))([0-9]{1,3})(?=$|[^0-9])')
    >>> r.sub(lambda x: '%04d' % (int(x.group(1)),), 'dfbg345gf345', sys.maxint)
    'dfbg0345gf0345'
    >>> r.sub(lambda x: '%04d' % (int(x.group(1)),), '1x11x111x', sys.maxint)
    '0001x0011x0111x'
    >>> r.sub(lambda x: '%04d' % (int(x.group(1)),), 'x1x11x111x', sys.maxint)
    'x0001x0011x0111x'
    
    0 讨论(0)
  • 2020-12-05 13:52

    C# version

            string input = "/2009/5/song 01 of 12";
            string regExPattern = @"(\/\d{4}\/)(\d+)(\/song\s+)(\d+)(\s+of\s+)(\d+)";
            string output = Regex.Replace(input, regExPattern, callback =>
            {
                string yearPrefix = callback.Groups[1].Value;
                string digit1 = int.Parse(callback.Groups[2].Value).ToString("0000");
                string songText = callback.Groups[3].Value;
                string digit2 = int.Parse(callback.Groups[4].Value).ToString("0000");
                string ofText = callback.Groups[5].Value;
                string digit3 = int.Parse(callback.Groups[6].Value).ToString("0000");
                return $"{yearPrefix}{digit1}{songText}{digit2}{ofText}{digit3}";
            });
    
    0 讨论(0)
  • 2020-12-05 14:01

    Using c#:

    string result = Regex.Replace(input, @"\d+", me =>
    {
        return int.Parse(me.Value).ToString("0000");
    });
    
    0 讨论(0)
提交回复
热议问题