-2

i've been kicking my self for a while now with regex, and unable to find a proper solution. I've been trying to transform a string using Regex.Replace() method in C# which should prepend 0 to existing string if length is less than 5, the conversion might be as follow

Input String ----------- Output String
12345        ----------- 12345
123          ----------- 00123
123456       ----------- 123456

any help will be appreciated

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Mirza Talha
  • 75
  • 1
  • 6

3 Answers3

2

You can use String.PadLeft: "1234".PadLeft(5, '0')

Gerino
  • 1,943
  • 1
  • 16
  • 21
1

It can be like

var outputString = Regex.Replace(inputString, @"\d+", n => n.Value.PadLeft(5, '0'));

but you don't really need regex in this case.

0

You don't need any regex

if(str.Length < 5){
  for(var i = 0; i < 5 - str.length; i++)
      str = "0" + str;
}

The above is all you need. What you're doing is if the input string's Length is less than 5, you're just subtracting and looping, adding them.

Amit Joki
  • 58,320
  • 7
  • 77
  • 95
  • @MirzaTalha Why? Why place artificial restrictions on a solution? – mason Feb 12 '15 at 14:46
  • @mason because i don't want to change my code... it will result in re-deployment of the existing application – Mirza Talha Feb 12 '15 at 14:50
  • @MirzaTalha If you're asking for us to provide a regex, that means you're having to change the code anyways. Might as well use the proper tools for the job. Regex should only be used when there's absolutely no better option. – mason Feb 12 '15 at 14:51
  • @mason The regex is configurable from a configuration file, that is why i was asking for regex mate – Mirza Talha Feb 12 '15 at 15:10