Why does it fail on 123-456-7891?


  • 0
    P

    My Statement is:
    grep '^(\d{3})[- ]\d{3}-\d{4}$' file.txt

    When I run this locally against '123-456-7891' it returns it. Leetcode is saying that it doesn't.


  • 0
    C

    I think the reason may be the shell u are using. Are you sure you are using bash?
    I run your code and it doesn't work.
    As far as I know, for the grep in bash environment, the ( and { need to use with \ as \( and \{. Also, the \d will not work here, instead you need to use [0-9]. Quite wired to use, I know.
    Pls try again to see if it works.


  • 0
    W

    I installed bash with version 4.4, and try this on my computer:

    echo '123-456-7891' | grep -e '^\s*\(\(\d\{3\}-\|(\d\{3\}) \)\d\{3\}-\d\{4\}\)\s*$'
    

    It works.

    Then I put this pattern in OJ, it failed on 123-456-7891.

    I really want to know why this doesn't work.


  • 0

    If you use 'grep' directly, it takes pattern as Basic Regular Expression.
    Use '-e' option to 'grep' to apply Extended Regular Expression as catbaron- said.


  • 0
    C

    same to me. I my regular express is

    ^([0-9]{3}\-|\([0-9]{3}\) )[0-9]{3}\-[0-9]{4}$
    

    and if failed for this case and most of other cases (21/26) passed.
    really don't know why


Log in to reply
 

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