PHP正则表达式意外匹配

时间:2013-07-12 14:51:38

标签: php regex preg-match-all

我的PHP代码中有一个正则表达式,应该匹配每个数字和所有“运算符”+ - * / ^ r()我的正则表达式看起来像这样

/(?:(\d+(?:\.\d+)|(\+)|(-)|(\*)|(\/)|(\^)|(r)|(\()|(\))))/

当使用字符串preg_match_all($expression,"2+2",$results)进行测试时,它会让我回来

Array
(
    [0] => Array
        (
            [0] => '+'
        )

    [1] => Array
        (
            [0] => ''
        )

    [2] => Array
        (
            [0] => '+'
        )

    [3] => Array
        (
           [0] => ''
        )

    [4] => Array
        (
            [0] => ''
    )

    [5] => Array
        (
            [0] => ''
        )

    [6] => Array
        (
            [0] => ''
        )

    [7] => Array
        (
            [0] => ''
        )

    [8] => Array
        (    
            [0] => ''
        )

    [9] => Array
        (
            [0] => ''
        )

)

当(如果它正常)我应该得到这个

Array
(
    [0] => Array
        (
            [0] => '2'
            [1] => '+'
            [2] => '2'
        )

    [1] => Array
        (
            [0] => '2'
            [1] => ''
            [2] => '2'
        )

    [2] => Array
        (
            [0] => ''
            [1] => '+'
            [2] = > ''
        )

    [3] => Array
        (
           [0] => ''
           [1] => ''
           [2] => ''
        )

    [4] => Array
        (
           [0] => ''
           [1] => ''
           [2] => ''
        )
    ...

)

注意,它会为所有运营商返回类似的行为,它似乎完全忽略这些数字

注意,我需要单独的捕获组,因此每个结果都有不同的匹配索引

1 个答案:

答案 0 :(得分:1)

你可以这样做:

$pattern = '~\d+(?:\.\d+)?|[-+*/^r()]~';