【发布时间】:2012-03-31 00:31:45
【问题描述】:
php > preg_match("@/m(/[^/]+)+/t/?@", "/m/part/other-part/t", $m);
php > var_dump($m);
array(2) {
[0]=>
string(20) "/m/part/other-part/t"
[1]=>
string(11) "/other-part"
}
php > preg_match_all("@/m(/[^/]+)+/t/?@", "/m/part/other-part/t", $m);
php > var_dump($m);
array(2) {
[0]=>
array(1) {
[0]=>
string(20) "/m/part/other-part/t"
}
[1]=>
array(1) {
[0]=>
string(11) "/other-part"
}
}
在上述示例中,我希望捕获同时匹配 /part 和 /other-part,不幸的是,正则表达式 /m(/[^/]+)+/t/? 不能像我预期的那样捕获两者。
此捕获不应仅与此样本匹配,它应捕获捕获组的未定义重复次数;例如/m/part/other-part/and-another/more/t
更新: 鉴于这是预期的行为,我的问题是如何实现我的匹配?
【问题讨论】:
-
我希望捕获组由于量词
+而被重复应用 -
另外,“不起作用”在问题标题中也不好。事实上,量词确实像 PCRE 中宣布的那样工作。
-
@hakre 从标题中删除了不起作用的部分。根据您的回答,我的记忆似乎在欺骗我,因为我记得对捕获组进行了量化。
-
仔细看,我假设您想要捕获子组匹配,这是 PHP 不支持的,这是一个 javascript 示例:Can you retrieve multiple regex matches in JavaScript?。