in reply to Re: regex at word boundary
in thread regex at word boundary
You're right about the (??{code}) construct facilitating the use of regular expressions in detecting palindromes. Behold:
use strict; use warnings; my $string = "God dog"; my $re = qr/^ (.+) (??{ ( length $^N > 1 and lc $^N eq reverse lc $^N ) ? '' : '1\b2' }) $/ix; print "$string is", ($string =~ $re) ? "" : "n't", " a palindrome.\n";
One trick here; since (??{code}) must spawn a regular subexpression that will then be evaluated for truth, the code block I used plays a little trick. If the boolean test of reversability succeeds, the (??{code}) expression returns an empty string (which, in other words, adds no additional criteria to be matched). If the reversability test fails, the code returns a regular subexpression that can never succeed; a search for '1\b2' (in other words, the literal number one, followed by the literal number two, but with a word boundry sandwiched between; an impossibility). That way the outcome of the reversability test can force a failure to match for the entire regular expression.
Also, the use of $^N is a convenience described in perlvar and perlre. It contains the most recent parenthetical capture. That way you don't need to count capturing parens, not that it's an issue in this case.
By the way, in my solution I chose to accept palindromes regardless of whether they contain only alpha characters or not. Why? Wikipedia says, "A palindrome is a word, phrase, number or any other sequence of units (like a strand of DNA) which has the property of reading the same in either direction..." It also says that the position of spaces can usually be adjusted as necessary. My regexp doesn't accomodate that possibility; it treats space like any other character. But why not; it's just a proof of concept. ;)
Dave
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: regex at word boundary
by QM (Parson) on Dec 08, 2005 at 04:50 UTC | |
by davido (Cardinal) on Dec 08, 2005 at 05:03 UTC | |
by QM (Parson) on Dec 08, 2005 at 05:12 UTC | |
by davido (Cardinal) on Dec 08, 2005 at 05:10 UTC | |
by QM (Parson) on Dec 08, 2005 at 05:25 UTC | |
by davido (Cardinal) on Dec 08, 2005 at 05:57 UTC | |
by QM (Parson) on Dec 10, 2005 at 05:46 UTC | |
by davido (Cardinal) on Dec 10, 2005 at 05:56 UTC | |
by mikeraz (Friar) on Dec 12, 2005 at 16:08 UTC | |
by QM (Parson) on Dec 12, 2005 at 17:48 UTC | |
|