Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

searching palindromes with grep

1,170 views
Skip to first unread message

Manuel Moreno

unread,
Apr 23, 1999, 3:00:00 AM4/23/99
to

I was reading one of the Kerninghan's bibles and found an exercise
that I can't solve.

Kerninghan says to search palindromes (words spelled the same backwards
as forwards) in a dictionary using grep.

This is what I have done:
egrep '^(\(.\)\(.\)\(.\)\3\2\1)|(\(.\)\(.\)\5\4) ' $1

it is only for 4 and 6 letter words but it doesn't work; the error message
says:
egrep: Invalid back reference

it works when I search only for 6 letter words but it fails when I
add the grouping parentheses and | to test also for 4 letter words

Why does it fail?
Thanks a lot.

--
________________________________________________
/ /|
/ Quitar ANTIBASURA para contestar por e-mail / |
/ Remove ANTIBASURA to reply via e-mail / /
/ Manuel Moreno - Albacete - Spain / /
/ / /
/_______________________________________________/ /
|_______________________________________________|/

Ken Pizzini

unread,
Apr 24, 1999, 3:00:00 AM4/24/99
to
On Fri, 23 Apr 1999 20:34:36 +0200,
Manuel Moreno <mmorenoA...@interplanet.es> wrote:
>This is what I have done:
> egrep '^(\(.\)\(.\)\(.\)\3\2\1)|(\(.\)\(.\)\5\4) ' $1
>
>it is only for 4 and 6 letter words but it doesn't work; the error message
>says:
> egrep: Invalid back reference
>
>it works when I search only for 6 letter words but it fails when I
>add the grouping parentheses and | to test also for 4 letter words

First off, egrep does not want \'s before the parens --- this
makes the parens non-special. Next you need to re-count your
open parens: the one you added to group the alternation made
your counts go off by one. Finally, you proably want to
anchor on the right if its palindromes you're after (and not
just palindromic prefixes):
egrep '^((.)(.)(.)\4\3\2|(.)(.)\6\5)$' /usr/dict/words

--Ken Pizzini

Warning, spoiler follows...
(I'd rot13 it, except its the RE that needs obfuscating, not the text)



Extending your approach so as to get all palindromes up to 7 letters long:
egrep '^((.)(.)(.).?\4\3\2|(.)(.).?\6\5|(.).?\7|.)$' /usr/dict/words
Or, done more simply:
egrep '^(.?)(.?)(.?).?\3\2\1$' /usr/dict/words

Incidentally: using the wordlists on my machine, the only palidrome
longer than 7 letters that I can find is the questionable "tat-tat-tat"
entry in /usr/dict/web2a .

0 new messages