背景

本想每天刷一道 leetcode,保持学习,但第一道就被困住了
题目如下

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.

For 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

我的解法

#!/bin/bash
pattern1="^[0-9]{3}-[0-9]{3}-[0-9]{4}$"
pattern2="^\([0-9]{3}\) [0-9]{3}-[0-9]{4}$"

cat ./file.txt | while read line
do
#echo "ori=$line"
        if [[ $line =~ $pattern1 ]] || [[ $line =~ $pattern2 ]] ; then
                echo $line
        fi
done

结果是一个都没匹配出来

查找问题的时候,尝试改成

#!/bin/bash
pattern1="^[0-9]{3}-[0-9]{3}-[0-9]{4}$"
pattern2="^\([0-9]{3}\)\s[1][0-9]{3}-[0-9]{4}$"

cat ./file.txt | while read line
do

echo "ori=$line"
        if [[ $line =~ ^[0-9]{3}-[0-9]{3}-[0-9]{4}$ ]] || [[ $line =~ ^\([0-9]{3}\)' '[0-9]{3}-[0-9]{4}$ ]] ; then
                echo $line
        fi
done

输出符合期望,如果在正则表达式附近加上双引号,则一个都匹配不出来,便以为表达式不可以用字符串的形式,于是修改脚本为

#!/bin/bash
pattern1=^[0-9]{3}-[0-9]{3}-[0-9]{4}$
pattern2=^\([0-9]{3}\)' '[0-9]{3}-[0-9]{4}$

cat ./file.txt | while read line
do

echo "ori=$line"
        if [[ $line =~ ${pattern1} ]] || [[ $line =~ ${pattern2} ]] ; then
                echo $line
        fi
done

发现只有第一个正则表达式 work 了,第二个依然没有匹配出来

那么如果我想用变量的方式让第二个正则表达式 work,该怎么修改?


↙↙↙阅读原文可查看相关链接,并与作者交流