Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Try this in Regexp palindrome

by inman (Curate)
on Mar 21, 2005 at 11:23 UTC ( [id://441179]=note: print w/replies, xml ) Need Help??


in reply to Try this in Regexp palindrome

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://441179]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (5)
As of 2024-04-25 08:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found