[Leetcode]193.valid-phone-numbers

题目

  1. 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.

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

解法1

# Read from the file file.txt and output all valid phone numbers to stdout.
cat file.txt | grep -P '(^\(\d{3}\) \d{3}-\d{4}$)|(^\d{3}-\d{3}-\d{4}$)' 
grep -P '^(\d{3}-|\(\d{3}\) )\d{3}-\d{4}$' file.txt
  • \ 转义符: to escape next one trailing character
   -P, --perl-regexp
          Interpret the pattern as a Perl-compatible regular expression (PCRE).  
          This is experimental and grep -P may warn of unimplemented features.

解法2

sed -n -r '/^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$/p' file.txt
   -n, --quiet, --silent
         suppress automatic printing of pattern space
  -E, -r, --regexp-extended
         use extended regular expressions in the script (for portability use POSIX -E).

解法3

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

引用和推荐阅读:

https://leetcode.com/problems/valid-phone-numbers/

https://leetcode.com/problems/valid-phone-numbers/discuss/55481/Three-different-solutions-using-grep-sed-and-awk

该文章遵循创作共用版权协议 CC BY-NC 4.0,要求署名、非商业 、保持一致。在满足创作共用版权协议 CC BY-NC 4.0 的基础上可以转载,但请以超链接形式注明出处。文章仅代表作者的知识和看法,如有不同观点,可以回复并讨论。

你可能感兴趣的:([Leetcode]193.valid-phone-numbers)