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

前端 未结 5 1002
梦谈多话
梦谈多话 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 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'));
    

提交回复
热议问题