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
全部评论

相关推荐

暴杀流调参工作者:春招又试了一些岗位,现在投递很有意思,不仅要精心准备简历,投递官网还得把自己写的东西一条一条复制上去,阿里更是各个bu都有自己的官网,重复操作无数次,投完简历卡完学历了,又该写性格测评、能力测评,写完了又要写专业笔试,最近还有些公司搞了AI辅助编程笔试,有些还有AI面试,对着机器人话也听不明白录屏硬说,终于到了人工面试又要一二三四面,小组成员面主管面部门主管面hr面,次次都没出错机会,稍有不慎就是挂。 卡学历卡项目卡论文卡实习什么都卡,没有不卡的😂
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务