V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
marginleft
V2EX  ›  问与答

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

  •  
  •   marginleft · 2015-07-06 22:47:35 +08:00 · 2414 次点击
    这是一个创建于 3435 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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 条回复    2015-07-07 07:01:16 +08:00
    msg7086
        1
    msg7086  
       2015-07-06 23:01:11 +08:00
    帮你在我本机测了一下,返回的是空的。
    msg7086
        2
    msg7086  
       2015-07-06 23:02:37 +08:00
    顺便我把 grep -E 改成 grep -P 以后就能拿到结果了。
    18000rpm
        3
    18000rpm  
       2015-07-06 23:13:06 +08:00
    又是正则的版本问题
    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  
       2015-07-06 23:42:45 +08:00
    egrep '^(\([0-9]{3}\)\s|[0-9]{3}-)[0-9]{3}-[0-9]{4}$' file.txt
    marginleft
        5
    marginleft  
    OP
       2015-07-07 07:01:16 +08:00 via Android
    @msg7086
    @18000rpm
    @yangqi
    非常感谢!了解了。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1047 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 22ms · UTC 19:22 · PVG 03:22 · LAX 11:22 · JFK 14:22
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.