Regex Coding Exercise – Valid Phone Numbers


Regular Expressions (Regex) are very powerful and useful tool to describe patterns.

https://leetcode.com/problems/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.

For 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

The Regular Expression is:

^((\([0-9]{3}\) )|([0-9]{3}\-))[0-9]{3}\-[0-9]{4}$

^ denotes the start of the string.
$ denotes the end of the string.
[0-9] means numbers
{3} means 3 numbers and {4} means 4 numbers
(A)|(B) means match pattern A or pattern B
\( escapes the bracket

So, you can use grep with parameter -P to match the pattern.

grep -P "^((\([0-9]{3}\) )|([0-9]{3}\-))[0-9]{3}\-[0-9]{4}$" file.txt

Alternatively, you can use awk or sed.

sed -n -e '/^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$/p' file.txt
awk '/^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$/' file.txt

We can use
[[:digit:]]{3} or \d{3} to replace [0-9]{3}.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
318 words
Last Post: Using the Dynamic Programming Algorithm, the Depth First Search or Breadth First Search to Solve House Robber Problem (Largest Sum of Non-Adjacent Numbers)
Next Post: C# Example - Using Parallel ForEach to Improve Existing Code

The Permanent URL is: Regex Coding Exercise – Valid Phone Numbers (AMP Version)

Leave a Reply