Format string with dashes

Kevin picture Kevin · Oct 19, 2010 · Viewed 22k times · Source

I have a compressed string value I'm extracting from an import file. I need to format this into a parcel number, which is formatted as follows: ##-##-##-###-###. So therefore, the string "410151000640" should become "41-01-51-000-640". I can do this with the following code:

String.Format("{0:##-##-##-###-###}", Convert.ToInt64("410151000640"));

However, The string may not be all numbers; it could have a letter or two in there, and thus the conversion to the int will fail. Is there a way to do this on a string so every character, regardless of if it is a number or letter, will fit into the format correctly?

Answer

Yuriy Faktorovich picture Yuriy Faktorovich · Oct 19, 2010
Regex.Replace("410151000640", @"^(.{2})(.{2})(.{2})(.{3})(.{3})$", "$1-$2-$3-$4-$5");

Or the slightly shorter version

Regex.Replace("410151000640", @"^(..)(..)(..)(...)(...)$", "$1-$2-$3-$4-$5");