• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2839
  • Last Modified:

C# Regex Phone Number

I'm looking for a comprehensive Regex pattern for a north american phone number.  Regex isn't my strong suit so I thought I'd put it up here as I'm sure it's a common problem.  The main thing is that I want to capture anything that resembles a phone number.  It's only used to highlight suspected phone number in text for the user, so false positives are less worrysome than missed numbers...

The following entities should match:
(###)-###-####
(###).###.####
###-###-####
###.###.####
### ### ####
(###) ### ####
### ###-####
### ###.####

etc...

Basically, three number area code (optionally surrounded by parenthesis), with 7 digits following the area code.  Number groups can be delimited by spaces, dashes or dots, and shouldn't need to be consistent.  For example: 604 555-5555 or 604 555.5555 or (604)-555-5555 etc...

Thanks for your help.

sk
0
tradeline
Asked:
tradeline
  • 4
  • 2
2 Solutions
 
ozoCommented:
\b(\(\d{3}\)|\d{3})([-.]|\s+)?\d{3}([-.]|\s+)?\d{3}\b
0
 
dkloeckCommented:
Here is another way:
^(\(\d{3}\)|\d{3})(\.| |\-)\d{3}(\.| |\-)\d{4}$
0
 
dkloeckCommented:
ozo..at your solution 604 555-5555, as in the solution above, would not work
"shouldn't need to be consistent"
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
ozoCommented:
Sorry, I meant
\b(\(\d{3}\)|\d{3})([-.]|\s+)?\d{3}([-.]|\s+)?\d{4}\b
0
 
ozoCommented:
(\(\d{3}\)|\b\d{3})([-.]|\s+)?\d{3}([-.]|\s+)?\d{4}\b
0
 
tradelineAuthor Commented:
Thanks guys, one last thing, in order to match the phonenumber inside of any other given string, I assume that I can add an asterix to the beginning and end of the pattern?

For example, dkloeck's solution: ^(\(\d{3}\)|\d{3})(\.| |\-)\d{3}(\.| |\-)\d{4}$ changes to ??

Gracias.
0
 
ozoCommented:
(\(\d{3}\)|\b\d{3})(\.| |\-)\d{3}(\.| |\-)\d{4}\b
0

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

  • 4
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now