Comments on Regular Expressions

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s