There are two ways to write error-free programs; only the third one works. - Alan J Peris

the brown-dragon blog

Prime (Ir)Regular Expressions

2009-08-12

Many of us use regular expressions a lot for editing. Though limited in power they are immensely useful tools and can be very helpful.

Once in a while, however, you run across a regular expression that's totally useless but really really cool: I ran across this snippet that checks if any given number is prime!

    /1$|(11+?)1+$/

The number has to be represented as a string of 1's and this expression will match non-primes. Neat right?

Of course, as you can see, we aren't using "pure" regular expression (which are finite automata: fast, useful, but not very powerful) but regexps with backreferences (and non-greedy matching), which means the above will work in Perl or Ruby but not in any of my primary editors:  Vim, EMacs, or Sed.

So, for those of you who use Vim/EMacs/Sed, here are my "translations" of the given expression:

    EMacs: (defun re-prime? (num)
             (not (string-match "^1$\|^\(11+?\)\1+$" (make-string num ?1))))
    Vim: /^1$|^(111{-})1+$/
    Sed: /^1?$/{d;};h;G;s/1//;/(11+)n1+$/d;s/.*n//

Try 'em out - it's fun to figure out how they work!

Other Posts

(ordered by Tags then Date)