Leo's Technical Blog

We Should Master Regular Expressions

Introduction

user

Leo Soto


tips

We Should Master Regular Expressions

Posted by Leo Soto on .
Featured

tips

We Should Master Regular Expressions

Posted by Leo Soto on .

When someone tell us that every programmer should know regular expressions, it's not only about using them to validate or match input on our programs. After all, seems like many of us can live using split() and replace() and some ad-hoc code instead of learning regexps.

My point today is that they are also useful when coding. I just needed to replace every code that looked like this:

  
<mx:RemoteObject id="grabaMuestreosRemote" 
... 
fault="Alert.show('Problemas al grabar los muestreos')"/>  

To:

  
<mx:RemoteObject id="grabaMuestreosRemote" 
... 
fault="reportFault('Problemas al grabar los muestreos', event.fault)"/>  

The change is on the last line, replacing the alert by a slightly more involved logic (which lives inside the reportFault function).

Solution? Find/Replace, using regexps (this was done with eclipse, but every reasonable editor have this feature):

Find:fault="Alert.show('([^']*)')"

Replace With:fault="reportFault('$1', event.fault)"

Quick explanation: ( and ) matches literal parenthesis; they are escaped because they have their own special meaning on regexp: capturing. And they are using for capturing the string message inside quotes, on '([^'])'. That means: a single quote (') followed by any character which is not a single quote ([^']), repeated 0 or more times (), followed by a single quite ('). So the non-escaped parenthesis are used to capture (i.e, remember, store) what was found inside the quotes. Later, you use the captured value by specifying $1 on the replacement text. If you have more captures, they are labeled $2, $3 and so on.

By the way, I'm not a regexp master. In fact, I admit to frequently resort to ad-hoc code, especially if I'm in a hurry.

But the simple exercise of summing all the time spent on writing ad-hoc code, plus the time wasted doing non-trivial find & replace by hand, have convinced me to learn them, and hopefully master them.