【Leetcode Shell】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

第一次嘗試:
1
2
# Read from the file file.txt and output all valid phone numbers to stdout.
grep '[(0-9][0-9][0-9)][- ][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]' file.txt
思想:
1、剛開始以爲是要去除重複的號碼,後來仔細審題才發現,題目要求僅僅是去除格式不符合的號碼。
2、也就是說只需要輸出符合格式的號碼即可,於是想到了用正則表達式
3、使用grep過濾命令,[] 表示或,只要滿足裏面任意一個字符即可,如[Ss]表示大小寫的s都可以
                                      - 表示-本身,[- ]表示滿足-或者空格即可
                                      [0-9]表示一個數字字符
結果報錯:

錯誤原因:
忽略瞭如果電話號碼既包含(,又有數字開頭的邊界條件,這個確實不好想到。。

第二次嘗試:
1
grep '^(\{0,1\}[0-9]\{3\}\{0,1\}[- ][0-9]\{3\}-[0-9]\{4\}$' file.txt
思想:
加入了開頭標識符^,同時發現其實可以將[0-9][0-9][0-9]替換成[0-9]\{3\}
結果報錯:

錯誤原因:
第三個數字之後,不是)和空格,就是-。這個問題我沒有注意到

第三次嘗試:
1
grep "^(\{0,1\}[0-9]\{3\}\(-\|) \)[0-9]\{3\}-[0-9]\{4\}$" file.txt
思想:
第三個數字之後可以寫成\(-\|) \)表示接下來的子串是 或者 空格,其中 \ 是轉義字符,告訴系統 () 和 不是匹配字符串的一部分
通過man grep可以發現如下提示:
Basic vs Extended Regular Expressions
       In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?,  \+, \{, \|, \(, and \).
在基本正則表達式BRE中,?, +, {, |, (, )將失去其特殊意義,如果不加轉義字符\,則會被認爲是匹配字符串的一部分
結果報錯:

發現頭部又匹配出錯了,看來還是分析的不夠透徹。
認真研究(xxx) xxx-xxxxxxx-xxx-xxxx發現,原來頭部不是(xxx)空格就是xxx-
因此又是二選一的,那麼我們直接把這兩個選項加到頭部即可

第四次嘗試:
1
grep "\(^([0-9]\{3\}) \|^[0-9]\{3\}-\)[0-9]\{3\}-[0-9]\{4\}$" file.txt
思想:
\( (xxx)空格 \xxx- \xxx-xxxx

結果通過:

本題知識點:
一、grep過濾
       grep '匹配字符串表達式' 文件
二、基本正則表達式中特殊字符
       在基本正則表達式BRE中,?, +, {, |, (, )將失去其特殊意義,如果不加轉義字符\,則會被認爲是匹配字符串的一部分
三、對由多個字符組成的多個匹配子串,進行或操作
       需要用到 或運算符 和小括號 ( ),同時要注意對這些特殊字符進行轉義
       


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章