-3

How do I write a Perl Script that display lines containing only valid phone numbers anywhere on the line?

Let us assume that (888).888-8888 is a valid number, where 8 could be any number.

So the sample input is 

this is nota number
3214235234
(410).977-2132
my num is ((410.222-1231))
test 234 test

Output:
(410).977-2132
my num is ((410.222-1231))

Here is what i HAVE SO FAR

   if ($string =~ /^(?:(?:\+?1\s*(?:[.]\s*)?)?(?:\(\s*([.][2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$) {
        # is a number
    } else {
        # is not
    }

I think i may have wrong regular expression. Can you please help?

Sam
  • 3
  • 2
  • 6
    "I think i may have wrong regular expression." That's why you shouldn't blindly copy code you don't understand. The [Stack Overflow answer I assume you got that from](http://stackoverflow.com/a/123666/176646) is written for a much wider range of input than you're trying to support, including country codes and extensions. Of course, `(000).000-0000` is probably not a *valid* phone number...are you sure you want to match it? – ThisSuitIsBlackNot May 16 '16 at 20:58
  • Yes I want to match it – Sam May 16 '16 at 21:03
  • 1
    Why do you think you have the wrong regex? What input is it matching that you don't want matched or vice versa? – ysth May 16 '16 at 21:36
  • @ysth Besides the syntax error in the OP's code, the regex doesn't match the 410 area code. – ThisSuitIsBlackNot May 16 '16 at 22:03

1 Answers1

0

To catch lines with: (888).888-8888 or ((888.888-8888)) you can use this regex:

if ($string =~ /^.*?\({0,2}\d{3}\){0,2}\.\d{3}-\d{4}\){0,2}/) {
    # is a number
} else {
    # is not
}
paperazzo79
  • 345
  • 1
  • 12