又一种绑特定语言的题目,幸好我之前笔电装linux系统时有自己学过一下
题目:
Given a text file file.txt that contains a 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.
给定一个里面txt档,每行都有一串电话号码,印出所有符合格式的电话号码
这题用grep配合万用字元就能快速解决
grep -P "^(\d{3}-|\(\d{3}\) )\d{3}-\d{4}$" file.txt
-P表示perl相容模式(个人比较喜欢)
^,$分别表示字串的开头与结尾
|表或
\d表示0~9字元,\d{3}为三个0~9字元的意思
(,)表(,)字元,不让它们被误解有特殊涵意
这样就能找到符合格式的电话号码了
最后执行时间91ms(faster than 94.47%)
那我们下题见