|
|
 |
|
Title: Finding Palindromes
Submitter: David Baird
(other recipes)
Last Updated: 2004/11/02
Version no: 1.0
Category:
Miscellaneous
|
|
2 vote(s)
|
|
|
|
Description:
Use this reqular expression to find palindromes, sentences or words which are the same written backwards and forwards.
Usage: Text Source
/^(.*).?(?>(.*))(?(?{$1 ne reverse $2})(?!))/i
The license for this recipe is available here.
Discussion:
This regular expression is an example of some useful, yet not well know, regex constuctors:
(?> performs a match without backtracking
(? if the following assertion is true
(?{}) runs a block of Perl code
(?!) then fail
otherwise the match succeeds
Here are some palindromes, which will have to have their spaces and puctuation removed before using the palindrome regex:
Borrow or rob?
Dammit, I'm mad!
He won a Toyota now, eh?
I did, did I?
Yo, banana boy!
|
|
Add comment
|
|
Number of comments: 5
inefficient., Neil Kandalgaonkar, 2005/01/08
It should be pointed out that this is just a look-what-I-can-do-with-regexes sort of recipe. It is extremely inefficient. The correct solution:
print "palindrome!" if $str eq reverse $str;
Add comment
It is an example of some advanced regex notations, David Baird, 2005/05/24
I entered it as an educational example, so the comment that there is a better solution with a simple Perl function is correct. But taken as an example, it can be used to demonstrate some of the regex notations listed, especially in a Regex debugger.
Add comment
palindrome , Aashish Nagar, 2005/07/06
hello soory to tell u that but the sentence u have send are also not matching properly the simplest and this is not the way we do
Add comment
Well, not really, David Craig, 2005/10/01
For simple words, reverse is fine; This example is also stripping out spaces and punctuation.... it's a different beast.
Besides, it's a good example of a couple of advanced regex features, so kick back.
Add comment
nice example, rodrigo fernandes, 2007/07/12
"Yo, bannana boy!" pays the recipe!
Add comment
|
|
|
|
|
 |
|