正则表达式匹配顺序问题

时间:2015-11-09 19:27:51

标签: php regex

我有以下代码:

preg_match(
    '/(,\s?min\s?(?P<min>[\d]+)\s?)?(,\s?max\s?(?P<max>[\d]+)\s?)?/', 
    ',max 1, min 2', 
    $vars
);

因此,匹配结果为:

//var_dump($vars):

array (size=7)
  0 => string ',max 1' (length=6)
  1 => string '' (length=0)
  'min' => string '' (length=0)
  2 => string '' (length=0)
  3 => string ',max 1' (length=6)
  'max' => string '1' (length=1)
  4 => string '1' (length=1)

可以理解min的价值为空''

我需要帮助才能获得数据minmax的价值,无论它们出现在字符串中的顺序如何。

感谢。

2 个答案:

答案 0 :(得分:1)

要抓住minmax而不管其顺序如何,您可以使用此基于交替的正则表达式:

\b(?:min\h+\K(?<min>\d+)|max\h+\K(?<max>\d+))\b

RegEx Demo

使用捕获的组名minmaxpreg_match_all函数调用后从结果数组中提取值。

答案 1 :(得分:1)

您可以使用以下正则表达式:

(?J)(?:,\s?min\s?(?P<min>\d+)\s?)(?:,\s?max\s?(?P<max>\d+)\s?)?|(?:,\s?max\s?(?P<max>\d+)\s?)(?:,\s?min\s?(?P<min>\d+)\s?)?

请参阅regex demo

正则表达式基本上属于你的,我刚刚添加了(?J)修饰符,允许在同一个正则表达式中重用捕获名称,并添加了另一个minmax订单的替代方法。另外,我从\d左右删除了方括号。

Ideone demo

$re = '/(?J)(?:,\s?min\s?(?P<min>\d+)\s?)(?:,\s?max\s?(?P<max>\d+)\s?)?|(?:,\s?max\s?(?P<max>\d+)\s?)(?:,\s?min\s?(?P<min>\d+)\s?)?/'; 
if (preg_match($re, ",max 1, min 2", $matches)){
    print_r($matches["max"] . " = max and min = " . $matches["min"] . PHP_EOL);
}
if (preg_match($re, ",min 5, max 6", $matches)){
    print_r($matches["max"] . " = max and min = " . $matches["min"] . PHP_EOL);
}
if (preg_match($re, ", min 7", $matches)){
    print_r($matches["max"] . " = max and min = " . $matches["min"] . PHP_EOL);
}
if (preg_match($re, ",max 8", $matches)){
    print_r($matches["max"] . " = max and min = " . $matches["min"]);
}

结果:

1 = max and min = 2
6 = max and min = 5
 = max and min = 7
8 = max and min =