Regular Expressions in CoffeeScript are Awesome
1 min read

Let's face it, regular expressions aren't for everyone. It takes a special breed of developer to actually enjoy writing regular expressions. Although I enjoy them, the developer that comes after me may find that they are cryptic and hard to read. And yes, sometimes it takes me a little bit to decipher through an old regular expression that I wrote a while ago.

Take for example, the following regular expression. Can you tell what it is doing? If so... then great, but what about the developers you work with?

var emailPattern = /^([\w.-]+)@([\w.-]+)\.([a-zA-Z.]{2,6})$/i;
if ( "john.smith@gmail.com".match( emailPattern ) ) {
console.log( "E-mail is valid" );
} else {
console.log( "E-mail is invalid" );
}
view raw emailPattern.js hosted with ❤ by GitHub
One of the very cool things I like about CoffeeScript is that you can annotate your regular expressions! The following snippet of CoffeeScript compiles down to the equivalent JavaScript as seen in the above code sample. Yay ;)

emailPattern = /// ^ #begin of line
([\w.-]+) #one or more letters, numbers, _ . or -
@ #followed by an @ sign
([\w.-]+) #then one or more letters, numbers, _ . or -
\. #followed by a period
([a-zA-Z.]{2,6}) #followed by 2 to 6 letters or periods
$ ///i #end of line and ignore case
if "john.smith@gmail.com".match emailPattern
console.log "E-mail is valid"
else
console.log "E-mail is invalid"
view raw emailPattern.coffee hosted with ❤ by GitHub
Which code sample would you rather maintain? And more importantly which one would your co-worker be more likely to understand?

NOTE: The above email regular expression is very naive in it's logic. I based the above snippet from a Nettuts+ post entitled, 8 Regular Expressions You Should Know. There are much more comprehensive email regular expressions available on the internet, but I used the above one to show the value of annotation.

As a side note, some tools that I find helpful are Grant Skinner's Online RegExr Tool and I sometimes get inspiration for regular expressions at RegExLib.com. What tools or resources do you use for regular expressions?

Edit post on GitHub


Find the jQuery Bug #4: Animations Gone Wild
Differences Between jQuery .bind() vs .live() vs .delegate() vs .on()