用于匹配可能没有结束分隔符的项的正则表达式


Regular Expression to Match Items That May Not Have an Ending Delimiter

我需要匹配下面示例URL中的test1test3:

http://www.domain.com/:test1/test2/:test3

这个正则表达式没有做:

(:.*?/?)

任何想法吗?

这个可以:

$str = 'http://www.domain.com/:test1/test2/:test3';
preg_match_all('~:'w+~', $str, $matches);
var_dump($matches);
输出:

array(1) {
  [0] =>
  array(2) {
    [0] =>
    string(6) ":test1"
    [1] =>
    string(6) ":test3"
  }
}

解释:

~    starting delimiter
:    a colon
'w   a *word* char
+    as many of them as possible
~    ending delimiter

这是你想要的吗?

/:([^'/]+)/i

我想这可能对你有用:

$string = 'http://www.domain.com/:test1/test2/:test3';
preg_match_all('#:.*?/|:.*#i', $string, $matches);
var_dump($matches);

有一个小教程,解释如何正则表达式引擎解释?和*在这里:

http://www.regex-engine.com/demo.html重复