LeetCode: 193. Valid Phone Numbers

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.

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

解题思路

模式伪代码如下:

((数字数字数字-)|(\(数字数字数字\) ))(数字数字数字)-(数字数字数字数字)

AC 代码

# 1. ^ 表示需要在行的开始处进行匹配. 例如, ^abc 可以匹配 abc123 但不匹配 123abc.
# 2. $ 表示需要在行的末端进行匹配. 例如, abc$ 可以匹配 123abc 但不能匹配 abc123.
# 3. \d可以匹配一个数字.'00\d'可以匹配'007',但无法匹配'00A'.
# 4. {n}表示n个字符,用{n,m}表示n-m个字符. \d{3}表示匹配3个数字,例如'010'.
# 5. -P(grep): Interpret the pattern as a Perl-compatible regular expression (PCRE).

# grep -P '^((([0-9]{3}-)|(\([0-9]{3}\) ))[0-9]{3}-[0-9]{4})$' file.txt
grep -P '^(\d{3}-\d{3}-\d{4}|\(\d{3}\) \d{3}-\d{4})$' file.txt
全部评论

相关推荐

09-29 11:19
门头沟学院 Java
点赞 评论 收藏
分享
废铁汽车人:秋招真是牛鬼蛇神齐聚一堂
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务