简体   繁体   English

正则表达式以匹配可能没有结尾定界符的项目

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

I need to match both test1 and test3 in the sample URL below: 我需要在下面的示例URL中同时匹配test1test3

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

This regex isn't doing it: 这个正则表达式没有做到这一点:

(:.*?/?)

Any thoughts? 有什么想法吗?

那是您要找的东西吗?

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

This one will do: 这将做到:

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

Output: 输出:

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

Explanation: 说明:

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

I think that this might work for you : 我认为这可能对您有用:

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

There's a little tutorial which explains how regex engines interpret ? 有一个小教程,解释了正则表达式引擎如何解释? and * here: 和这里:

http://www.regex-engine.com/demo.html#repetition http://www.regex-engine.com/demo.html#repetition

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM