This is not something useful, but is surely the most interesting regexp I have come across,
A regexp that tests for prime numbers:
/^1?$|^(11+?)\1+$/
You can test it in perl by doing
$perl -e 'print "Prime\n" if (1 x shift) !~ /^1?$|^(11+?)\1+$/' 19
$Prime
$perl -e 'print "Prime\n" if (1 x shift) !~ /^1?$|^(11+?)\1+$/' 20
$
I think it is by Abigail from the perl community.
Edit:
For the people having hard time believing it works, here is an explanation:
In the test example, (1 x shift) creates a string of ones whose length is the number we are testing for primeness
The regexp actually finds if the number has any divisors other than one or itself => not prime.
^1?$ will return true for 1 which is not prime.
^(11+?)\1+$ which is more complicated does the following.
^(11+?) means start by trying to see if it can find 11 at the beginning of the string, \1 means repeated + means at least once and matches the string from start to end ^ and $ => this is a check if the length is divisible by two.
ex: 8 (11111111) would match 11 repeated 4 times
9 (111111111) would yield 11 repeated 4 times but with a final 1 left at the end, so the string is not matched form beginning to end.
The neat part is that when it cannot match,it backtracks and tries to match 111 repeated in the same way => check if divisible by three ...
9 (111111111) will be matched with 111 repeated 3 times exactly from start to end.
And so forth, if any match is found the number has a divisor and is not prime otherwise the number has no divisors and is prime.
A number like 7 would never match. 11,111,1111,11111,111111 leave some unmatched ones at the end and 1111111 is not "repeated at least once", so the regexp never matches -> no divisors -> number is prime