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

前端 未结 5 1000
梦谈多话
梦谈多话 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.

提交回复
热议问题