我在哪里可以找到匹配数字范围的php正则表达式生成器?

时间:2011-06-28 00:59:37

标签: php regex

我正在寻找类似这样的东西:How to generate a regular expression at runtime to match a numeric range但用php编写。

2 个答案:

答案 0 :(得分:3)

在这里回答你的问题,因为代码块的评论很糟糕。我不会直接翻译这样的声明,因为它几乎不可读。这样分开要容易得多:

if ($n == $m) { // max/min ranges are the same, so just look for that number of characters
    $format = "\{$n\}";   // {n}
} elseif ($n == 1) { // min range is 1, so use the max
    $format = "\{1,$m\}";  // {1,m}
} else { // arbitary n->m range
    $format = "\{$n,$m\}";  // {n,m}
}

它可以在PHP中作为三元组完成,但它的调试难以辨认/不可能:

$format = ($n == $m) ? "\{$n\}" : (($n == 1) ? "\{1,$m\}" : "\{$n,$m\}");

答案 1 :(得分:0)

我认为这应该有效:

class NumericRangeRegexGenerator {

private function baseRange($num,$up, $leading1) {

    $c = $num[0];
    $low  = $up ? $c : ($leading1 ? '1' : '0');
    $high = $up ? '9': $c;

    if (strlen($num) == 1)
        return $this->charClass($low, $high);

    $re = $c . "(" . $this->baseRange(substr($num,1), $up, false) . ")";

    if ($up) $low++; else $high--;

    if ($low <= $high)
        $re .= "|" . $this->charClass($low, $high) . $this->nDigits(strlen($num) - 1);

    return $re;
}

private function charClass($b, $e) {
    //String.format(b==e ? "%c" : e-b>1 ? "[%c-%c]" : "[%c%c]", b, e); (in java)
    if ($b == $e) {
        $format = $b; 
    } elseif ($e-$b>1) {
        $format = '['.$b.'-'.$e.']';
    } else {
        $format = '['.$b.$e.']';
    }
    return $format;
}

private function nDigits($n, $m=null) {
    //String.format(n==m ? n==1 ? "":"{%d}":"{%d,%d}", n, m) (in java)

            if($m===null){
                nDigits($n, $n);
            }

    if ($n == $m) { // max/min ranges are the same, so just look for that number of characters
        $format = "\{$n\}";   // {n}
    } elseif ($n == 1) { // min range is 1, so use the max
        $format = "\{1,$m\}";  // {1,m}
    } else { // arbitary n->m range
        $format = "\{$n,$m\}";  // {n,m}
    }
    return "[0-9]" . $format;
}

private function eqLengths($from, $to) {

    $fc = $from[0];
            $tc = $to[0];

    if (strlen($from) == 1 && strlen($to) == 1)
        return $this->charClass($fc, $tc);

    if ($fc == $tc)
        return $fc . "(".$this->rangeRegex(substr($from,1), substr($to,1)).")";

    $re = $fc . "(" . $this->baseRange(substr($from,1), true, false) . ")|"
              . $tc . "(" . $this->baseRange(substr($to,1),  false, false) . ")";

    if (++$fc <= --$tc)
        $re .= "|" . $this->charClass($fc, $tc) . $this->nDigits(strlen($from) - 1);

    return $re;
}    

private function nonEqLengths($from, $to) {
    $re = $this->baseRange($from,true,false) . "|" . $this->baseRange($to,false,true);
    if (strlen($to) - strlen($from) > 1)
        $re .= "|[1-9]" . $this->nDigits(strlen($from), strlen($to) - 2);
    return $re;
}

public function rangeRegex($n, $m) {
    return strlen($n) == strlen($m) ? $this->eqLengths($n, $m) : $this->nonEqLengths($n, $m);
}

}