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条)

报告相同问题?

悬赏问题

  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面