193 - Valid Phone Numbers

来源:互联网 发布:系统编程 编辑:程序博客网 时间:2024/05/16 12:13

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-4567123 456 7890(123) 456-7890
Your script should output the following valid phone numbers:
987-123-4567(123) 456-7890

Subscribe to see which companies asked this question

思路分析:

此题的关键,正则表达式的匹配。

知识点

1、匹配必须发生在目标字符串的开头处,^必须出现在表达式的最前面才具有定位符作用。例如,“^o”与“ok”中的o匹配,但与“book”中的o不匹配。如果设置了RegExp对象实例的Multiline属性,^还会与行首匹配,即与“\n”、“\r”之后的位置匹配。光盘文件7.6.htm演示了该字符的使用,代码如下所示。

2、$匹配输入字符串的结束位置。如果设置了RegExp对象的Multiline属性,$也匹配“\n”或“\r”之前的位置。

3、x|y匹配x或y。例如,“z|food”能匹配“z”或“food”(此处请谨慎)。“(z|f)ood”则匹配“zood”或“food”。

4、[xyz]字符集合。匹配所包含的任意一个字符。例如,“[abc]”可以匹配“plain”中的“a”。

5、[^xyz]负值字符集合。匹配未包含的任意字符。例如,“[^abc]”可以匹配“plain”中的“plin”。

6、\  将下一个字符标记符、或一个向后引用、或一个八进制转义符。例如,“\\n”匹配\n。“\n”匹配换行符。序列“\\”匹配“\”而“\(”则匹配“(”。即相当于多种编程语言中都有的“转义字符”的概念。

sed -nr '/^(\([0-9]{3}\) ){1}[0-9]{3}-[0-9]{4}$|^([0-9]{3}-){2}[0-9]{4}$/p' file.txt


0 0
原创粉丝点击