PHP正则表达式将命令与参数匹配

时间:2017-06-01 17:29:37

标签: php regex string

我在PHP中使用此代码

case preg_match('/\/start( .*)?/', $text):
    echo "got you";
break;

使用这个正则表达式我需要做的就是捕获以下结构: $ text需要:

  • /起动

  • / start xyz

哪里" xyz"代表随机内容。这是正则表达式应该接受的两种格式。出于某种原因,我的正则表达式似乎没有按预期工作。

1 个答案:

答案 0 :(得分:1)

这应该可以解决问题:

^\/start\s?[\S]*$

以下是python DEMO中的一个示例:

import re

textlist = ["^/start xyz","/start","/start not to match"]

regex = "^/start\s?[\S]*$"

for text in textlist:
    thematch = re.search(regex, text)
    if thematch:
        print ("match found")
    else:
        print ("no match sir!")

它正在做什么:行以/ start开头并且可能有空格,然后可能有任何数量的非空格(包括没有),然后行结束。

希望这有帮助!

EDIT;
这段代码的PHP版本。

$textlist = array("^/start xyz","/start","/start not to match");

$regex = "#^/start\s?[\S]*$#";

foreach($textlist as $text){
    preg_match($regex, $text, $thematch);
    if ($thematch){
        print ("match found\n");
    }else{
        print ("no match sir!\n");
    }
}

在这里演示:https://3v4l.org/OFpnG