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: "page 012" Input: "page 123", Ouput: "page 123"
What's the best way to do this with Regex.Replace?
At this moment I use this but the results are 001, 0012, 00123.
string sInput = "page 1";
sInput = Regex.Replace(sInput,@"\d+",@"00$&");
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.
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'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With