Regex匹配特定的数字组合模式


Regex to match certain pattern of number combinations

我正在寻找在php中从以下格式获取数据的正则表达式:

"1,2,3;7,1,3;1" returns an $matches array with "(1,2,3,7,1,3,1)"
"1" returns an $matches with "(1)"
"1;1;3;5;7;10;999" returns an $matches array with "(1,1,3,5,7,10,999)"
"1,1,1;2,5;3,4" doesn't pass since numbers are repeating within semicolon boundaries
"2,3,4;5,;" doesn't pass since it doesn't satisfy the format.

(例子中的引号是为了让它们更容易阅读;它们不应该出现在实际结果中。

格式是由逗号或分号分隔的数字,并且在分号内它们彼此不重复。不接受其他格式

我试过/(^('d{1,3})$)|(([0-9]+)([,|;]{1}[0-9]+)+)/,但它不起作用。我也试过/[0-9]+([,|;]{1}[0-9]+)+/,但它也不起作用。当我得到$matches数组时,它没有上面所描述的我需要的值。

我在PHP 5.2中这样做。谢谢。

这个特殊的问题有太多的逻辑正则表达式是实用的;这就是你如何用常规代码解决它的方法:

// reduction function - keeps merging comma separated arguments
// until there's a duplicate or invalid item
function join_unique(&$result, $item)
{
    if ($result === false) {
        return false;
    }
    $items = explode(',', $item);
    $numbers = array_filter($items, 'is_numeric');
    if (count($items) != count($numbers)) {
        return false;
    }
    $unique = array_unique($numbers);
    if (count($unique) != count($numbers)) {
        return false;
    }
    return array_merge($result, $numbers);
}
// main function - parse a string of comma / semi-colon separated values
function parse_nrs($str)
{
    return array_reduce(explode(';', $str), 'join_unique', array());
}
var_dump(parse_nrs('1,2,3;7,1,3;1'));
var_dump(parse_nrs('1'));
var_dump(parse_nrs('1;1;3;5;7;10;999'));
var_dump(parse_nrs('1,1,1;2,5;3,4'));
var_dump(parse_nrs('2,3,4;5,;'));
输出:

array(7) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
  [3]=>
  string(1) "7"
  [4]=>
  string(1) "1"
  [5]=>
  string(1) "3"
  [6]=>
  string(1) "1"
}
array(1) {
  [0]=>
  string(1) "1"
}
array(7) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "1"
  [2]=>
  string(1) "3"
  [3]=>
  string(1) "5"
  [4]=>
  string(1) "7"
  [5]=>
  string(2) "10"
  [6]=>
  string(3) "999"
}
bool(false)
bool(false)

参见:array_reduce() array_unique()

这是不可能在一个步骤中完成的。首先,您需要检查在分号边界内重复数字的要求,如果满足,则检查拆分字符串。

例如:

if (!preg_match('/'b('d+),[^;]*'b'1'b/', $string)) {
    $matches = preg_split('/[,;]/', $string);
} else {
    $matches = NULL;
}

Ideone: http://ideone.com/Y8xf1N