majorpayne27
majorpayne27

Reputation: 181

C# Regex Number Formatting

I'm not very good with regular expressions and am trying to do use them to format a number.

The original number will be something like 05XX-123, and I'd like to append zeros to make it 05XX-000123 (the number after the hyphen should have zeros prepended until its length is six). If I mix regex and string operations I can achieve this with the following solution...

Regex regex = Regex(@"^([0-9]{2})([A-Za-z]{2})-([0-9]*)$");
Match match = regex.Match("05XX-123");
string result = match.Groups[1].Value + match.Groups[2].Value + "-" + match.Groups[3].Value.PadLeft(6, '0');

However, I would like to avoid the third line because I would like these transformations to be able to be defined at runtime.

It seems like something similar to this should be possible, but I'm just not quite sure how to prepend the zeroes to the third group (the number after the letters).

Regex regex = Regex(@"^([0-9]{2})([A-Za-z]{2})-([0-9]*)$");
string result = regex.Replace("05XX-123", "$1$2-$3");

Obviously the above example just returns the same value as was provided, but it seems like I should be able to do something to the $3 group to prepend the zeros to make $3's length six.

Any help would be greatly appreciated, thanks!

Upvotes: 1

Views: 2774

Answers (1)

Michael Dean
Michael Dean

Reputation: 1576

Try this (unless you need regex for something else):

string[] parts = originalNumber.Split(new char[] {'-'});
string newNumber = parts[0] + "-" + parts[1].PadLeft(6, '0');

Edit:

A different regex alternative:

Regex regEx = new Regex(@"^([0-9]{2}[A-Z]{2}\-)([0-9]*)$", RegexOptions.IgnoreCase);
string result = regEx.Replace("05XX-123",m => m.Groups[1].Value + m.Groups[2].Value.PadLeft(6, '0'));

Upvotes: 4

Related Questions