By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
457,759 Members | 1,255 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 457,759 IT Pros & Developers. It's quick & easy.

Regular Expression for a Phone Number

P: n/a

The problem is in the word boundary \b. A leading "("
will match as a word boundary before it gets to the test
for a "(". Changing the expression to:

(?n)(\b|\()1?[\s-]?\(?(?<areaCode>[2-9]\d\d)?\)?[\s-]?(?
<firstThree>[2-9]\d\d)(?:\s|-)?(?<lastFour>\d{4})\b

will allow the leading "(" to be captured in the match,
but has the uninteded consequence of matching "(1 (219)
555-5555)" as well, so you probably need to use something
ilke this:

(?n)((\()|(\b1?[\s-]?\(?))(?<areaCode>[2-9]\d\d)?\)?[\s-]?
(?<firstThree>[2-9]\d\d)(?:\s|-)?(?<lastFour>\d{4})\b

I didn't do a lot of testing with this expression, though,
so make sure you run through all your previous tests
before using it.

It looks like the revised expression runs about 25% slower
than the original, so if you need to run this a lot, you
may prefer your original version.
Brian Davis
www.KnowDotNet.com - tutorials, tips, tricks, and tools
for .NET

-----Original Message-----
Hello,

I'm trying to write a regular expression that will catch
and group a US phone number in pretty much any format. (eg
1-xxx-xxx-xxxx or (xxx) xxx-xxxx or xxxxxxxxxx or xxx- xxxx etc)
This is what i have so far:
\b1?[\s-]?\(?(?<areaCode>[2-9]\d\d)?\)?[\s-]?(? <firstThree>[2-9]\d\d)(?:\s|-)?(?<lastFour>\d{4})\b
This seems to be catching most things but it doesn't match
the first "(" part of an area code. Any ideas on how to fixthis or some number formats I may be missing?

Thanks,
Jeff
.

Nov 15 '05 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.