dongza6247 2014-02-11 19:54
浏览 46
已采纳

从字符串中准确捕获2个单词

I'm using regex to parse a command that looks like this:

!hello foo bar

I would like to capture foo and bar. If the command is passed anything but 2 arguments then I want the regex to fail.

Here's my regex so far:

^!hello (.*)$

I know that {2} can be used to limit the amount captured, but I'm not sure exactly how to use it in this situation.

Thanks

  • 写回答

2条回答 默认 最新

  • duanji9264 2014-02-11 19:58
    关注

    Instead of the greedy (.*), I would recommend using something more specific like \w+ to match one or more "word" characters. Since whitespace may be insignificant, separate them with \s+. Rather than trying to use {2}, since you expect exactly two separated by whitespace, it is easier to spell each group out literally as \w+ with the whitespace requirement in between.

    ^!hello\s+(\w+)\s+(\w+)$
    

    If you don't actually need to reuse the arguments, remove the ().

    ^!hello\s+\w+\s+\w+$
    
    $pattern = '/^!hello\s+\w+\s+\w+$/';
    echo preg_match($pattern, '!hello foo bar');
    // 1
    echo preg_match($pattern, '!hello foo bar baz');
    // 0
    echo preg_match($pattern, '!hello "foo bar" baz');
    // 0
    // Note a numeric argument matches \w+... If that isn't allowed
    // you should use [A-Za-z]+ instead or just [a-z]+ and add the /i flag
    echo preg_match($pattern, '!hello 123 baz');
    // 1
    echo preg_match($pattern, '!hello a$1 baz');
    // 0
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度