Leetcode 193.Valid Phone Numbers

Leetcode 193.Valid Phone Numbers

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://*.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