又一種綁特定語言的題目,幸好我之前筆電裝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%)
那我們下題見