Mac OS X coding

Comments on Regular Expressions

March 29, 2007 · No Comments

N.B. This post is adapted from my general blog

I really like regular expressions. This real-world example shows you why:

I have this C++ test code generated by a script written by someone else. Due to a minor bug in the script, it generates invalid code like if (blah != ) , where that space should have been 0. Now there are about 500 instances of these. For this time, I can get away with using the search/replace feature in Visual Studio, Xcode, or similar editors. But what if there were inconsistent copies of if(blah!=) where each copy had different spacing levels between the if and opening parens, and = and closing parens, etc?

You can use regular expressions to do a search replace:

(you can try other editors too, possibly even Visual Studio, Xcode, etc.)

In Vim, in command mode

:%s/if\s*(blah\s*!=\s*)/if (blah != 0)/gc

translation: %s -> command for search replace
\s* stands for 0 or more spaces
the first set of /…/ delimit the string we are looking for
the second set of /…/ delimit what we want to replace the string with
the gc at the end tell vim to ask us before replacing each instance.

So, you see, regular expressions can really save you time.

Categories: Regular Expressions

0 responses so far ↓

  • There are no comments yet...Kick things off by filling out the form below.

Leave a Comment