LeetCode193——有效電話號碼

我的LeetCode代碼倉:https://github.com/617076674/LeetCode

原題鏈接:https://leetcode-cn.com/problems/valid-phone-numbers/description/

題目描述:

知識點:Linux常用指令、正則表達式

思路一:grep命令

grep命令用於查找文件裏符合條件的字符串,其中-P選項可以讓grep使用perl的正則表達式語法。

Bash腳本:

grep -P '^(\d{3}-|\(\d{3}\) )\d{3}-\d{4}$' file.txt

LeetCode解題報告:

思路二:sed命令

sed命令是利用script來處理文本文件,其中-n選項僅顯示script處理後的結果,取消將模式空間中的內容自動打印出來,-r選項表示在腳本中使用擴展正則表達式。

Bash腳本:

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

LeetCode解題報告:

思路三:awk命令

Bash腳本:

awk '/^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$/' file.txt

LeetCode解題報告: