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

前端 未结 5 965
梦谈多话
梦谈多话 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: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"));
    

提交回复
热议问题