PHP 正则表达式无法让它工作


PHP regex cannot get it working?

我正在尝试制作一个正则表达式以符合特定条件,但我无法让它按照我想要的方式工作。

我目前的正则表达式是

'/S(?:[0-9]){2}E(?:[0-9]){2}/i'

我希望它做的是符合以下标准

S

至少一位数字0-9

可以0-9的可选数字

E

至少一位数字0-9

可以0-9的可选数字

如果可能的话,我也希望它将双精度数与单个数字相匹配,我按照互联网上的教程组成了正则表达式,但认为我错过了一些东西。

谢谢。。。

试试这个:

<?php
$reg = "#S'd{1,2}E'd{1,2}#";
$tests = array('S11E22', 'S1E2', 'S11E2', 'S1E22', 'S111E222', 'S111E', 'SE', 'S0E0');
foreach ($tests as $test) {
    echo "Testing $test... ";
    if (preg_match($reg, $test)) {
        echo "Match!";
    } else {
        echo "No Match";
    } 
    echo "'n";
}

输出:

Testing S11E22... Match!
Testing S1E2... Match!
Testing S11E2... Match!
Testing S1E22... Match!
Testing S111E222... No Match
Testing S111E... No Match
Testing SE... No Match
Testing S0E0... Match!

解释:

 $reg = "#S'd{1,2}E'd{1,2}#";
          ^ ^  ^  ^ ^  ^
          | |  |  | |  |
    Match S |  |  | |  One or two times
  Match digit  |  | Match a digit
One or two times  Match the letter E

编辑

或者,您可以使用类似的东西来执行此操作

$reg = '#S'd'd?E'd'd?#';

也就是说,S 后跟数字,可能后跟另一个数字?......等等。