Valid Phone Numbers Problem
Description
LeetCode Problem 193.
Given a text file file.txt that contains a 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.
Example:
Assume that file.txt has the following content:
987-123-4567
123 456 7890
(123) 456-7890
Your script should output the following valid phone numbers:
987-123-4567
(123) 456-7890
Solution
Approach: Anchored regular expression
There are only two accepted shapes, so one regular expression that must match the whole line is enough.
^and$anchor the pattern to the full line, so extra characters before or after the number make it invalid.- The alternation
[0-9]{3}-|\([0-9]{3}\)matches the start of either form:xxx-or(xxx)(note the space after the parenthesis). - The rest,
[0-9]{3}-[0-9]{4}, is common to both formats.
Without the anchors, a line such as 123 456-7890-1 would be accepted because a valid number appears inside it. grep -E and awk both do the job; awk is used here.
# Print the lines of file.txt that are a valid phone number.
awk '/^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$/' file.txt