d--b
d--b

Reputation: 5779

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

Upvotes: 3

Views: 1703

Answers (1)

anubhava
anubhava

Reputation: 785058

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

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

num = "31";
Regex.Replace(num, @"\b\d\b", "0$&");
//=> 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


In case digit can appear in the middle of the word then you can use lookarounds regex like this:

num = Console.WriteLine(Regex.Replace(num, @"(?<!\d)\d(?!\d)", "0$&"));

Upvotes: 4

Related Questions