What does this code snippet do?…
Those with several years development expertise will realize it’s a regular expression. But even the most astute guru will take a few moments to determine that it checks the validity of an email address. Only a superior subset of that group will comprehend that it’s fairly superficial and won’t check all possibilities.
Individual rules are normally straight-forward, e.g.
[a-z] matches a single lowercase character and
c.t matches a three letter string starting with ‘c’ and ending with ‘t’ — such as ‘cat’. However, when rules are combined, an indecipherable string of seemingly random codes starts to appear. The one above is relatively simple compared to many you’ll find in the wild.
Creating your own regular expressions is difficult enough and many of us resort to using the force. But it’s easy compared to parsing someone else’s code — which is normally written by someone who has an irrational aversion to comments!
Admittedly, you’ll still need a reasonable understanding of pattern matching, but it’s far more evident the expression is analyzing an email address.
Behind the scenes, RegExper is a Ruby application which translates regular expressions into an SVG image. The SVG is embedded in the page, but it should be possible to extract or copy it for use in your own documentation.
If you’d like to make improvements or automate the process, the project is open source and available to download or fork from github.com/javallone/regexper.
RegExper is incredibly clever. While there are plenty of tools to help you devise and test regular expressions, very few allow you to parse or reverse-engineer existing code. I’ve not found any which does it quite so prettily either.
Add RegExper to your toolkit and you’ll be parsing regular expressions with renewed enthusiasm. Probably.
Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.
The Principles of Beautiful Web Design, 4th Edition
Docker for Web Developers
HTML5 Games: Novice to Ninja