正则表达式:lookbehind断言

时间:2013-10-23 01:20:31

标签: php regex

我使用 ((\d)(\d(?!\2))((?<!\3)\d(?!\3)))\1 来匹配不同行的任意数字:

234234,345345,359359 但不匹配211211,355355 (删除lookbehind断言将匹配这些)

我在PHP中使用preg_match()运行时发现模式出错,因为偏移的长度必须固定,但在其他debuger中测试时可以正常(在这种情况下我使用kodos)

preg_match_all():编译失败:lookbehind断言在偏移量23处不是固定长度

是否有任何替代的模式可以匹配上面的排序数字? 245245或其他符合ABCABC格式模式的数字。

3 个答案:

答案 0 :(得分:1)

如果3位数必须不同,您可以使用:

((\d)(?!.?\2)(\d)(?!\3)\d)\1

但如果允许545545,您可以使用:

((\d)(?!\2)(\d)(?!\3)\d)\1

答案 1 :(得分:0)

问题在于外观,这使它成为一个前瞻,似乎对我有用regex101

((\d)(\d(?!\2))(?!\3)(\d(?!\3)))\1

答案 2 :(得分:0)

只是使用前瞻而不是外观?

((\d)(?!\2)(\d)(?!\2|\3)\d)\1

Regex Explainer解释:

--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    (                        group and capture to \2:
--------------------------------------------------------------------------------
      \d                       digits (0-9)
--------------------------------------------------------------------------------
    )                        end of \2
--------------------------------------------------------------------------------
    (?!                      look ahead to see if there is not:
--------------------------------------------------------------------------------
      \2                       what was matched by capture \2
--------------------------------------------------------------------------------
    )                        end of look-ahead
--------------------------------------------------------------------------------
    (                        group and capture to \3:
--------------------------------------------------------------------------------
      \d                       digits (0-9)
--------------------------------------------------------------------------------
    )                        end of \3
--------------------------------------------------------------------------------
    (?!                      look ahead to see if there is not:
--------------------------------------------------------------------------------
      \2                       what was matched by capture \2
--------------------------------------------------------------------------------
     |                        OR
--------------------------------------------------------------------------------
      \3                       what was matched by capture \3
--------------------------------------------------------------------------------
    )                        end of look-ahead
--------------------------------------------------------------------------------
    \d                       digits (0-9)
--------------------------------------------------------------------------------
  )                        end of \1
--------------------------------------------------------------------------------
  \1                       what was matched by capture \1