Wednesday, May 23, 2018

c# - Phone Number formatting using Regex












I have an unformatted phone number (guaranteed to be 10 digits) and an unformatted extension (could be null, blank or any number of numbers). I need to put them together into a "friendly" string. I thought I'd concatenate them, then format the concatenation using a Regex.Replace. Here's the unit test I'm using to try various regexes before I plug one in:



    [Test, Ignore("Sandbox, does not test production code")]
public void TestPhoneRegex()
{
string number = "1234567890";
string extension = "";

var formattedContactNumber =
Regex.Replace("{0} x{1}".FormatWith(number, extension),

@"^(\d{3})[ -]?(\d{3})[ -]?(\d{4})( x\d+)?",
@"$1-$2-$3$4");

Debug.WriteLine("{0} x{1}".FormatWith(number, extension));
Debug.WriteLine(formattedContactNumber);

Assert.AreEqual("123-456-7890", formattedContactNumber);
}



The expected formatted string is the formatted phone number, without the "x" and extension. However, the last capture group is matching the "x" with or without a number behind it, so instead of "123-456-7890" I get "123-456-7890 x". This is the last bit of development that needs to be tied down before a release. Help?


Answer



x isn't matched by your regex, so it isn't replaced put of the string. Try this regex instead:



@"^(\d{3})[ -]?(\d{3})[ -]?(\d{4}) x(\d*)


In the new regex x isn't optional - it will always be there according to your code (If you do want it to be optional you can use ?x?(\d*)). Also, we're using \d*, so make sure the last group will always match, even when it's empty.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...