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.


In reply to Re: Try this in Regexp palindrome by inman
in thread Try this in Regexp palindrome by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.