1

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!

1 Answer 1

4

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'));
6
  • This works, although I'd like to completely avoid string operations. The reason being that I'd like the transformation to be defined at runtime. Apr 28, 2011 at 3:41
  • @majorpayne27: constructing regex pattern at runtime is not much easier than changing parameters of string functions IMO
    – Dyppl
    Apr 28, 2011 at 3:46
  • Using string functions would definitely be easier, but it isn't an option that is available to me. I need to be able to change the output format without recompiling. Apr 28, 2011 at 3:57
  • 1
    I'm not sure if that's possible without having some type of callback (I haven't seen it done without one) or running through multiple regex passes. I added a different method above, but if you want the output to be dynamic at runtime, how many different output formats would you be expecting to support? How would they be defined and executed? Apr 28, 2011 at 4:40
  • 1
    +1, though maybe you were looking for m => m.Groups[1].Value + m.Groups[2].Value.PadLeft(6, '0')
    – Kobi
    Apr 28, 2011 at 4:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.