LeetCode 193: Valid Phone Numbers

Given a text file file.txt that contains list of phone numbers (one per line), write a one liner bash script to print all valid phone numbers.

You may assume that a valid phone number must appear in one of the following two formats: (xxx) xxx-xxxx or xxx-xxx-xxxx. (x means a digit)

You may also assume each line in the text file must not contain leading or trailing white spaces.

assume that file.txt has the following content:

123 456 7890
(123) 456-7890

Your script should output the following valid phone numbers:

(123) 456-7890



grep -E ‘^(\([0-9]{3}\)\s|[0-9]{3}-)[0-9]{3}-[0-9]{4}’ file.txt

grep -E ‘^\([0-9]{3}\)\s[0-9]{3}-[0-9]{4}$|^[0-9]{3}-[0-9]{3}-[0-9]{4}$’ file.txt

egrep -o “^(([0-9]{3}\-)|(\([0-9]{3}\) )){1}[0-9]{3}\-[0-9]{4}$” file.txt

grepP ‘^(\(\d{3}\) |\d{3}-)\d{3}-\d{4}$’ file.txt



\d is a Perl-flavored regular expression, which Mac OS X’s grep -E supports directly. However, in GNU grep you need to use grep -P to enable this feature. Obviously the OJ’s server uses GNU/Linux, so that’s why your script works on your Mac but failed on the OJ website.


  1. Escaping - with a backslash is unnecessary, you can just type - instead of \-.
  2. Using cat and a pipe is also unnecessary, you can feed the filename to grep directly.

1. egrep -o: output the exact match

2. ^: match the beginning of line

3. ([0-9]{3}\-): match exactly 3 digits followed by ‘-‘, e.g. xxx-.

4. (\([0-9]{3}\) ): match 3 digits between ( and ) followed by a single space, e.g. (xxx) .

5. (([0-9]{3}\-)|(\([0-9]{3}\) )){1}: combine the two previous matches from point 3 and 4: matches or 3 digits followed by ‘-‘, e.g. xxx-, or 3 digits between ( and ) followed by a single space, e.g. (xxx) , exactly {1} time, because the phone number can be in the format

6. (xxx) xxx-xxxx or xxx-xxx-xxxx.

7. [0-9]{3}\-: match exactly 3 digits followed by ‘-‘

8. [0-9]{4}: match exactly 4 digits

9. $: match end of line

grep: try to grep the content inside the file.
find: find the file with indexed name.
egrep:equivalent to grep -E


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s