0

I need to format my telephone numbers in a specific way. Unfortunately business rules prohibit me from doing this up front. (separate input boxes etc..)

The format needs to be +1-xxx-xxx-xxxx where the "+1" is constant. (We don't do business internationally)

Here is my regex pattern to test the input:

"\\D*([2-9]\\d{2})(\\D*)([2-9]\\d{2})(\\D*)(\\d{4})\\D*"

(which I stole from somewhere else)

Then I perform a regex.Replace() like so:

regex.Replace(telephoneNumber, "+1-$1-$3-$5"); **THIS IS WHERE IT BLOWS UP**

If my telephone number already has the "+1" in the string, it prepends another so that I get +1-+1-xxx-xxx-xxxx

Can someone please help?

2
  • You could try adding a (+1-)? at the front of your regex to accomodate for the telephone numbers that already have the +1... Commented Jul 9, 2015 at 17:22
  • 1
    Highly recommend you grab a phone formatting library for c# - then you can let it handle international numbers as well. Commented Jul 9, 2015 at 17:28

3 Answers 3

2

You can add (?:\+1\D*)? to catch an optional prefix before the number. As it's caught it will be replaced if it's there.

You don't need to use \D* before and after the number. As they are optional, they don't change anything.

You don't need to capture the parts that you won't use, that makes it easier to see what ends up in the replacement.

str = Regex.Replace(str, @"(?:\+1\D*)?([2-9]\d{2})\D*([2-9]\d{2})\D*(\d{4})", "+1-$1-$2-$3");

You might consider using something more specific than \D* for the separators though, for example [\- /]?. With a too non-specific pattern you risk catching something that's not a phone number, for example changing "I have 234 cats, 528 dogs and 4509 horses." into "I have +1-234-528-4509 horses.".

str = Regex.Replace(str, @"(?:\+1[\- /]?)?([2-9]\d{2})[\- /]?([2-9]\d{2})[\- /]?(\d{4})", "+1-$1-$2-$3");
Sign up to request clarification or add additional context in comments.

Comments

1

try something like this to make things more readable:

Regex rxPhoneNumber = new Regex( @"
  ^                             # anchor the start-of-match to start-of-text
  \D*                           # - allow and ignore any leading non-digits
  1?                            # - we'll allow (and ignore) a leading 1 (as in 1-800-123-4567
  \D*                           # - allow and ignore any non-digits following that
  (?<areaCode>[2-9]\d\d)        # - required 3-digit area code
  \D*                           # - allow and ignore any non-digits following the area code
  (?<exchangeCode>[2-9]\d\d)    # - required 3-digit exchange code (central office)
  \D*                           # - allow and ignore any non-digits following the C.O.
  (?<subscriberNumber>\d\d\d\d) # - required 4-digit subscriber number
  \D*                           # - allow and ignore any non-digits following the subscriber number
  $                             # - followed the end-of-text.
  " ,
  RegexOptions.IgnorePatternWhitespace|RegexOptions.ExplicitCapture
);

string input = "voice: 1 (234) 567/1234 (leave a message)" ;
bool isValid = rxPhoneNumber.IsMatch(input) ;
string tidied = rxPhoneNumber.Replace( input , "+1-${areaCode}-${exchangeCode}-${subscriberNumber}" ) ;

which will give tidied the desired value

+1-234-567-1234

4 Comments

I like the suggestion... Thank you
Note: If you anchor the pattern to the beginning and ending of the string, the string can't contain any digits other than the ones in the phone number.
@Guffa, exactly so: the point is to validate/standardize a phone number entered by the user. There shouldn't be any other digits there.
@NicholasCarey: But the pattern allows for anything else to be there, just not digits. For example "voice: 1 (234) 567/1234 (leave a msg, I get back 2 u)" will fail.
0

You can use the following regex

\D*(\+1-)?([2-9]\d{2})\D*([2-9]\d{2})\D*(\d{4})\D*

And the replacement string:

$1$2-$3-$4

Here is a demo

This is a kind of an adjustment of the regex you had. If you need to match the whole numbers, I'd use

(\+1-)?\b([2-9]\d{2})\D*([2-9]\d{2})\D*(\d{4})\b

See demo 2

enter image description here

Also, if the hyphen in \+1- is optional, add a ?: \+1-?.

To make the regex safer, I'd replace \D* (0 or more non-digit symbols) with some character class containing known separators, e.g [ /-]* (matching /, spaces and -s).

1 Comment

I hope my answer was at least helpful. My laptop half burnt, my son peed in the bed, but I tried to come up with some ideas for you :)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.