Developer's Notebook: Mastering (your fear of) regular expressions

Regular expressions are one of the most difficult programming concepts for novices and journeymen to wrap their heads around. Take a look at most any blog posting about RegExes and the comments will invariably be littered with words like "hate," "pain" and "AAAAARGH!"

Once you get comfortable with them, though, regular expressions become one of the most powerful tools in your programming arsenal. For Ajax/JavaScript developers, they can lend power and elegance to everything from form validators to keystroke interpreters to JSON, CSS and DOM parsers - in short, many of the thing you'll want to do on the client side of any powerful webapp. Take a look under the hood of any respected Ajax/DHTML library and you'll see RegEx literals being used liberally.

It's no secret that I'm big on programming books, especially O'Reilly ones, but I can think of few books that have been more useful than Jeffrey E. F. Friedl's "Mastering Regular Expressions". One difficult aspect of JavaScript regular expressions is their syntax, which is completely different from the better-known Perl variety. Friedl steps back from the implementation details of individual RegEx engines to explain the central concepts common to them all. After having this book for a year, I still refer to it so often that I can't say when I'll be ready to graduate to Tony Stubblebine's "Regular Expression Pocket Reference." In the meantime, when I'm away from my copy of the Friedl book, there are plenty of online resources to guide me.

Cheat sheets & quick references

These links don't offer really in-depth tutorials, but they do show you the JavaScript RegEx syntax at a glance.

Interactive terminals

Apparently, everybody and their mother decided to build a little DHTML/Ajax app to let you create regular expressions, run arbitrary text against them, and check out the results. This is a fantastic way to play with the technology and get more confident in your abilities. Here are 9 different implementations of the same basic idea. I haven't used all of them, so let me know in the comments which are most useful.

And for the over-achievers

For those of you so advanced in your RegEx powers that you've hit the limitations of the built-in JavaScript implementation, check out XRegExp, an open-source regular-expression library that supports named capture and other advanced features.

Technorati tags