1

I need to recognize a phone number on a long string, now I am using this regex

(((\d)(-)?)+){7,15}|\*\d{3,10}|\d{3,10}\*

but that does not recognize any one of these formats:

(734) 555 1212
(734) 555.1212
(734) 555-1212
(734) 5551212
(734)5551212

with "()",

How can I change it to support also these formats?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Shahar Zer
  • 37
  • 1
  • 8
  • 1
    I've [answered](http://stackoverflow.com/a/30140087/3764814) a very similar question yesterday. In the answer, I tried to explain the general methodology to get the expression you need. – Lucas Trzesniewski May 10 '15 at 10:21

2 Answers2

0

You can use this updated regex:

\(\d{3}\)\s*\d{3}[\s.-]?\d{4}\b|\*\d{3,10}|\d{3,10}\*

See demo

Explanation of the updated part:

  • \( - literal round brackets
  • \d{3} - match 3 digits
  • \) - closing round bracket
  • \s* - optional whitespace
  • \d{3} - 3 digits
  • [\s.-]? - 0 or 1 whitespace or dot or hyphen
  • \d{4} - 4 digits.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

Your regular expression is very lenient - it will recognize 1-2-3-4-5-6-7- as a valid phone number, which would of course be a false positive. If you would like to keep the same level of leniency, replace the optional dash - in your expression with an optional character group that includes parentheses, spaces, and a dash:

[(]?(((\d)([() .-]+)?)+){7,18}|\*\d{3,10}|\d{3,10}\*

Demo.

Of course this expression will bring even more false positives, because it accepts anything that looks remotely close to a phone number.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 1
    @ShaharZer You are welcome. If the problem is solved, consider accepting the answer to let others know that you are no longer looking for additional help with the question. – Sergey Kalinichenko May 10 '15 at 11:22