matthew ephraim

Archive for the ‘general programming’ Category

Syntax Highlighting is Fun

Tuesday, February 3rd, 2009
JavaScript

Freedom of regular expression

Saturday, November 3rd, 2007

The concept of regular expressions is one of those computer science ideas that still feels like magic to me. You take what looks like a string of nonsense, feed it into a computer and, suddenly, strange and wonderful things begin to happen. I still feel a sense of fascination when I come up with a regular expression that gives me exactly what I wanted. Does that mean I’m not experienced enough yet?

Tonight I wrote this magic spell:

Regex
/{\s*(\w+)\.*(\w*)\s*([\w=\[\]"'_-\s]*)}/

What is it used for? Well, I’m rewriting a simple template system for a CakePHP site and I wanted to do it the right way with regular expressions this time instead of the original find and replace method I used the first time through.

For example, if a user on the site entered a template tag like this:

{Collection.images ul_attributes[id="images"]}

My template parser would use the regular expression to find that tag and replace it with this:

XHTML
<ul id="images">
    <li><img src="..." /></li>
    <li><img src="..." /></li>
</ul>

I made the expression overly complex to account for linebreaks and other extra spacing that the user might add when entering the keys. And it works! That’s the exciting part. Every time I get a regular expression right I feel like this