Similar Problems

Similar Problems not available

Valid Phone Numbers - Leetcode Solution

Companies:

LeetCode:  Valid Phone Numbers Leetcode Solution

Difficulty: Unknown

Topics: unknown  

Problem Statement:

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.

Solution:

To solve this problem, we can use Regular Expressions (Regex) to match the pattern of valid phone numbers. We can use grep command with regex pattern to filter out only valid phone numbers from the given input.

Here is the one-liner bash script solution:

grep -P "^(\d{3}-|\(\d{3}\) )\d{3}-\d{4}$" file.txt

Explanation:

  • The ^ and $ characters are used to define the start and end of the line respectively.
  • The -P option with grep command is used to enable Perl-style regular expression pattern matching.
  • The \d symbol matches any digit from 0 to 9.
  • The {3} means that the preceding digit matches exactly 3 times.
  • The ( and ) characters are used to group digits together.
  • The | character is used to specify either grouping.
  • The space between the parentheses is optional.
  • The \ character is used to escape special characters to their literal equivalents.
  • The grep command matches and prints all phone numbers that meet the specified pattern.

Example:

Suppose the file.txt contains the following data:

987-123-4556
(123) 456-7890
mmmm 123) 456-7890
(111) 111-1111

The above bash script will produce the following output:

987-123-4556
(123) 456-7890

So, the output contains only the valid phone numbers from the given input.

Valid Phone Numbers Solution Code

1