代码之家  ›  专栏  ›  技术社区  ›  Peter Ajtai

为什么这个正则表达式使用“not”和backref,需要一个惰性匹配?

  •  2
  • Peter Ajtai  · 技术社区  · 14 年前

    使用not时 ^ not

    例如:

    <?php
    preg_match('/(t)[^\1]*\1/', 'is this test ok', $matches);
    echo $matches[0];
    ?>
    

    Will output this test ,而不是 this t ,尽管事实上 t 不匹配 [^\1] /(t)[^\1]*?\1/ to match this t .

    此外

    preg_match('/t[^t]*t/', 'is this test ok', $matches);
    

    does match only this t .

    发生了什么,我误解了什么?

    2 回复  |  直到 14 年前
        1
  •  5
  •   Mark Byers    14 年前

    它不起作用,因为 \1 这里不是字符类中的反向引用。这个 \1

    你可以用消极的环视来获得你想要的效果:

    '/(t)(?:(?!\1).)*\1/'
    
        2
  •  2
  •   Ben Blank    14 年前

    [^\1] 意思是“除了 1 ".

    /(t)(?:(?!\1).)*\1/ .

    (?:...) 是非捕获组

    (?!...)

    (?!\1). ,何时 \1 是单个字符,表示“任何不匹配的字符”