Pages

Wednesday, August 3, 2011

Format string with Regex

Just discovered something cool today, and most of you guys probably knew it already, but this was new to me, and I am kinda excited sharing it - we can format strings with Regex. That's pretty awesome.

The way we do it is:
Regex.Replace("unformatted string", "regex", "format");
This returns the formatted string. Simple.

For example, To format a phone number string, "1234567899" to (123) 456-7899, we could do something like below:
Regex.Replace(PhoneNumber,@"(\d{3})(\d{3})(\d{4})","($1) $2-$3");

No comments:

Post a Comment