https://leetcode.com/problems/valid-phone-numbers/description/
Shell腳本題目:給file.txt ,輸出複合格式的電話號碼。思路是使用正則,但是有幾個坑。
-
注意grep -E 與grep -P 的區別 https://www.jianshu.com/p/e1acfb7989b2
-E 其實是擴展支持| 與& 這種方式,-P纔是Perl正則 - 注意正則使用^ 和 $ 包圍精確匹配
- 剛開始使用cat 和read 讀取文件,發現要麼多個空格省略成一個,要麼修改IFS爲'' 但是又處理不了換行。https://stackoverflow.com/questions/7314044/use-bash-to-read-line-by-line-and-keep-space
實際上grep 直接讀取文件就好了。
grep -P "^(\d{3}-|\(\d{3}\) )\d{3}-\d{4}$" file.txt