The definition of a palindrome is a piece of text that can be read both forwards and backwards. Punctuation and whitespace is ignored. Case is also ignored.
The base regexp for a potential midpoint is /(.).?\1/. The problem is that a single piece of input may contain multiple palindromic fragments in a larger palindrome. You will therefore need to test all midpoints.
The code below creates a series of regular expressions that increasingly match longer palindromes.
#! /usr/bin/perl -w
use strict;
use warnings;
my $data = shift;
$data =~ s/\W//g;
my @groups;
my @refs;
for (1 .. (length $data) / 2)
{
push @groups, "(.)";
unshift @refs, "\\$_";
my $regex = join('',@groups).".?".join('',@refs);
print "$regex\n";
while ($data =~ /$regex/ig)
{
print "$&\n";
}
}
The above code needs to run within the limits of the total number of matches that are available in the Perl regex engine.
This regular expression looks simpler but uses in pattern code execution which is not supported across all regex engines (but it is in Perl so you will be OK).
/(.*).?(?{reverse($1)})/.
A hybrid approach would be to locate the midpoint using the /(.).?\1/ regex and then compare the leading part and the reverse of the trailing parts. |