d--b d--b - 1 year ago 78
C# Question

Substitute number with 2 digits in regex

I have some input that is an integer stored as a string that may have 1 or 2 digits. I would like to know if it is possible to come up with a regex pattern and substitution string that allows me to add a 0 at the front of any input that has only one digit.

ie. I'd like to find pattern and subst such that:

Regex.Replace("1",pattern,subst); // returns "01"
Regex.Replace("31",pattern,subst); // returns "31"

Edit: the question is specific to C# regex. Please do not answer to provide alternative methods

Answer Source

Using regex you can use word boundaries around a single digit:

string num = "5";
Regex.Replace(num, @"\b(\d)\b", "0$1");
//=> 05

num = "31";
Regex.Replace(num, @"\b(\d)\b", "0$1");
//=> 31

Code Demo

Regex \b(\d)\b will match a single digit with word boundaries on either side to ensure we're only matching a single digit.

More Infor about Word boundary

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download