Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

regex

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$&");
like image 980
Bastien Vandamme Avatar asked Jul 27 '11 09:07

Bastien Vandamme


2 Answers

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.

like image 101
Sven Avatar answered Sep 16 '22 15:09

Sven


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'));
like image 24
Guffa Avatar answered Sep 19 '22 15:09

Guffa