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


Where can I find a php regex generator that matches number ranges?

我正在寻找这样的东西:如何在运行时生成一个正则表达式,以匹配数值范围,但使用php编写。

在这里回答您的问题,因为注释对代码块来说很可怕。我不会直接翻译这样的声明,因为它几乎无法阅读。像这样拆开要容易得多:

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'}");

我认为这应该有效:

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);
}

}