V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
marginleft
V2EX  ›  问与答

leetcode: Valid Phone Numbers 通过不了。求解

  •  
  •   marginleft · Jul 6, 2015 · 2911 views
    This topic created in 3954 days ago, the information mentioned may be changed or developed.
    https://leetcode.com/problems/valid-phone-numbers/

    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

    -----------
    我的答案是:
    grep -E '\d\d\d-\d\d\d-\d\d\d\d|\(\d\d\d\)\s*\d\d\d-\d\d\d\d' file.txt

    系统提示:
    Submission Result: Wrong Answer
    Input: 123-456-7891
    Output:
    Expected: 123-456-7891

    但是在我的本机上,明明可以grep出来啊。
    百思不得其解。求指导。
    5 replies    2015-07-07 07:01:16 +08:00
    msg7086
        1
    msg7086  
       Jul 6, 2015
    帮你在我本机测了一下,返回的是空的。
    msg7086
        2
    msg7086  
       Jul 6, 2015
    顺便我把 grep -E 改成 grep -P 以后就能拿到结果了。
    18000rpm
        3
    18000rpm  
       Jul 6, 2015
    又是正则的版本问题
    osx -E 能出来,ubuntu 下 -E 不行

    grep's default mode is (iirc) POSIX regex, and \d is pcre.
    http://stackoverflow.com/a/6901221/1019566
    yangqi
        4
    yangqi  
       Jul 6, 2015
    egrep '^(\([0-9]{3}\)\s|[0-9]{3}-)[0-9]{3}-[0-9]{4}$' file.txt
    marginleft
        5
    marginleft  
    OP
       Jul 7, 2015 via Android
    @msg7086
    @18000rpm
    @yangqi
    非常感谢!了解了。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   863 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 44ms · UTC 18:49 · PVG 02:49 · LAX 11:49 · JFK 14:49
    ♥ Do have faith in what you're doing.