[LeetCode]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

题目大意:

给定一个文本文件file.txt,包含一列电话号码(每行一个),写一个单行bash脚本输出全部有效的电话号码。
你可以假设有效的电话号码符合下列两种格式之一:(xxx) xxx-xxxx or xxx-xxx-xxxx. (x 代表数字)
同时也可以假设文本文件中的每一行都不包含前导或者后缀空格。
例如,假设file.txt包含下面的内容:

987-123-4567
123 456 7890
(123) 456-7890

你的脚本应该输出下列有效的电话号码:

987-123-4567
(123) 456-7890

Bash脚本:

# Read from the file file.txt and output all valid phone numbers to stdout.
cat file.txt | grep -Eo '^(\([0-9]{3}\) ){1}[0-9]{3}-[0-9]{4}$|^([0-9]{3}-){2}[0-9]{4}$'

其中:

^(\([0-9]{3}\) ){1}[0-9]{3}-[0-9]{4}$ 匹配形如(123) 456-7890的电话号码

^([0-9]{3}-){2}[0-9]{4}$ 匹配形如987-123-4567的电话号码

本文链接:http://bookshadow.com/weblog/2015/03/26/leetcode-valid-phone-numbers/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

暂无评论

张贴您的评论