Saturday, January 10, 2009

Regex and Prime Numbers

I was looking for articles and examples on advanced regular expressions when I came across this amazing expression that prints prime numbers:


perl -e 'print "PRIME" if (1 x shift) !~ /^(11+)\1+$/' xxxx


I knew regular expressions were powerful but this is pure ninja stuff. The origin of this expression is attributed to Abigail who also maintains the Regex::Common module. Abigail is a frequent poster to the comp.lang.perl.misc newsgroup and this example originated as a one-line program in one of Abigail’s sign-off signatures. Since then, it has been commented on within the group on a few occasions and with a few other variations.

You can find explanations on how and why this works here or here.

No comments: