Grep -e solution with detailed explanation, good for those new to regex


  • 21
    S
    grep -e '\(^[0-9]\{3\}-[0-9]\{3\}-[0-9]\{4\}$\)' -e '\(^([0-9]\{3\})[ ]\{1\}[0-9]\{3\}-\([0-9]\{4\}\)$\)'  file.txt
    
    1. In Bash, we use \ to escape next one trailing character;
    2. ^ is used to denote the beginning of a line
    3. $ is used to denote the end of a line
    4. {M} is used to denote to match exactly M times of the previous occurence/regex
    5. (...) is used to group pattern/regex together

    Back to this problem: it requires us to match two patterns, for better readability, I used -e and separate the two patterns into two regexes, the first one matches this case: xxx-xxx-xxxx and the second one matches this case: (xxx) xxx-xxxx

    Please vote this post up if you find it helpful for your understanding!

    Cheers!


  • 0
    K

    Thank you for that awesome explanation!! :)

    grep -e '\(^[0-9]\{3\}-[0-9]\{3\}-[0-9]\{4\}$\)' -e '\(^([0-9]\{3\})[ ]\{1\}[0-9]\{3\}-\([0-9]\{4\}\)$\)'  file.txt
    
    grep -e  '\(^[0-9]\{3\}-[0-9]\{3\}-[0-9]\{4\}$\)' -e '\(^([0-9]\{3\})[ ]\{1\}[0-9]\{3\}-[0-9]\{4\}$\)'  file.txt
    

    Is there a specific reason as to why you added the \(\) in \([0-9]\{4\}\) for the second regex match?


  • 0
    I

    Thanks! I have written a shorter version with the help of |

    grep -e "^\([0-9]\{3\}-\|([0-9]\{3\}) \)[0-9]\{3\}-[0-9]\{4\}$" telephone.txt
    

    note:

    • remember use \ to escape |;
    • ( and ) also need to be escaped when they are used following ^ as showing its bound;

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.