LeetCode Solution, Easy, 193. Valid Phone Numbers
Play this article
193. 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.
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
題目翻譯
檔案 file.txt
中儲存了每一行的電話資料,需要寫一個 script 來驗證每一行的電話格式,並且輸出出來。其格式有兩種 (xxx) xxx-xxxx
和 xxx-xxx-xxxx
。
解法解析
主要解法是使用了 Regex 來去做格式判別,分別針對 (xxx) xxx-xxxx
和 xxx-xxx-xxxx
編寫各自的 Regex。
解法範例
Bash
# Read from the file file.txt and output all valid phone numbers to stdout.
egrep -e '^\([0-9]{3}\) [0-9]{3}-[0-9]{4}$' -e '^[0-9]{3}-[0-9]{3}-[0-9]{4}$' file.txt