In C#, how can I use Regex.Replace to add leading zeroes (if possible)?

前端 未结 5 966
梦谈多话
梦谈多话 2021-01-18 07:15

I would like to add a certain number of leading zeroes to a number in a string. For example:

Input: \"page 1\", Output: \"page 001\" Input: \"page 12\", Ouput: \"pa

相关标签:
5条回答
  • 2021-01-18 07:58

    Regex replacement expressions cannot be used for this purpose. However, Regex.Replace has an overload that takes a delegate allowing you to do custom processing for the replacement. In this case, I'm searching for all numeric values and replacing them with the same value padded to three characters lengths.

    string input = "Page 1";
    string result = Regex.Replace(input, @"\d+", m => m.Value.PadLeft(3, '0'));
    

    On a sidenote, I do not recommend using Hungarian prefixes in C# code. They offer no real advantages and common style guides for .Net advise against using them.

    0 讨论(0)
  • 2021-01-18 08:01

    Use a callback for the replacement, and the String.PadLeft method to pad the digits:

    string input = "page 1";
    input = Regex.Replace(input, @"\d+", m => m.Value.PadLeft(3, '0'));
    
    0 讨论(0)
  • 2021-01-18 08:02
    string sInput = "page 1";
    //sInput = Regex.Replace(sInput, @"\d+", @"00$&");
    string result = Regex.Replace(sInput, @"\d+", me =>
    {
        return int.Parse(me.Value).ToString("000");
    });
    
    0 讨论(0)
  • 2021-01-18 08:08
    string sInput = "page 1 followed by page 12 and finally page 123";
    
    string sOutput = Regex.Replace(sInput, "[0-9]{1,2}", m => int.Parse(m.Value).ToString("000"));
    
    0 讨论(0)
  • 2021-01-18 08:13
    var result = Regex.Replace(sInput, @"\d+", m => int.Parse(m.Value).ToString("00#"));
    
    0 讨论(0)
提交回复
热议问题