获取所有匹配的组PREG PHP flavor

时间:2016-01-27 13:40:39

标签: php regex

模式:'/x(?: (\d))+/i'

字符串:x 1 2 3 4 5

退回:1 Match Position[11-13] '5'

我想抓住所有可能的重复,或者每组返回1个结果?

我想要以下内容:

期望的输出:

MATCH 1
1.  [4-5]   `1`
2.  [6-7]   `2`
3.  [8-9]   `3`
4.  [10-11] `4`
5.  [12-13] `5`

我只能通过复制粘贴组来实现,但这不是我想要的。我想要动态群组捕获

模式:x(?: (\d))(?: (\d))(?: (\d))(?: (\d))(?: (\d))

1 个答案:

答案 0 :(得分:1)

您无法使用一个组捕获多个文本,然后使用PCRE访问它们。相反,您可以将整个子字符串与\d+(?:\s+\d+)*匹配,然后用空格分割:

$re2 = '~\d+(?:\s+\d+)*~';
if (preg_match($re2, $str, $match2)) {
    print_r(preg_split("/\\s+/", $match2[0]));
}

或者,使用基于\G的正则表达式返回多个匹配

(?:x|(?!^)\G)\s*\K\d+

请参阅demo

这是PHP demo

$str = "x 1 2 3 4 5"; 
$re1 = '~(?:x|(?!^)\G)\s*\K\d+~'; 
preg_match_all($re1, $str, $matches);
var_dump($matches);

此处,(?:x|(?!^)\G)充当前导边界(仅在x或每次成功匹配后匹配空格和数字)。遇到数字时,到目前为止匹配的所有字符都会被\K运算符省略。