[pcre-dev] Help with palindrome matching

Top Page
Delete this message
Author: Spoon Reloaded
Date:  
To: pcre-dev
Subject: [pcre-dev] Help with palindrome matching
In Perl I can match palindromes (strings that read the same forwards
and backwards), and only palindromes, using the following pattern:
/^(.?|(.)(?1)\2)$/
Explanation: a palindrome is either a string of 0 or 1 characters
(base case), or it is a palindrome surrounded by the same character on
both sides (here the (.) and the \2 match the character that is the
same on both sides, and the (?1) is a recursive call to the main part
of the palindrome pattern). The ^ and $ ensure that the palindrome
takes up the whole string.

However, this pattern does not work in PCRE. It doesn't seem to match
any string longer than 1 character. I don't understand why. I've
played around with many variations, to no avail. I've tried things
like /^((.)(?:|(?1))\2)$|^((.)(?:.|(?3))\4)$/, but it doesn't match
simple palindromes like "ababababababa".

I was wondering if you guys could (1) explain why my pattern does not
work, (2) tell me if there is anything simple that I can change to
make it work as I want, and (3) if not, tell me if there is any
pattern that can match palindromes as I want in PCRE.

Thanks,