Sunday, September 19, 2010

Matching palindromes in PCRE regex

$palindrome = '/(?x)
^
  (?:
      (.) (?=
              .*
              (
                \1
                (?(2) \2 | )
              )
              $
          )
  )*
  .?
  \2?
$

/';
(see with testcases on ideone.com)

This is "better" than the one given in the man page, which is based on recursive subpattern matching which doesn't quite "work" because it's atomic.

Too lazy to explain how it works, so I'm just going to toss the bone to stackoverflow (see: How does this PCRE pattern detect palindromes?).

No comments:

Post a Comment