Friday, July 27, 2007

Useful Regexp in Emacs for C++

First press Ctrl-Alt-Shift-5 to get Query-Regexp-Replace
Then I want to find C-style casts in my .cpp file, and replace them with C++ style casts. For example:
GeoData *gd = (GeoData *)mThreeDData;

GeoData *gd = dynamic_cast<GeoData *>(mThreeDData);

First I figure out that this: (\w+ ?\*)[A-Za-z_]+
will find the expression I want. It's finding the parens, then \w is a 'word-constituent' which fits our type names nicely, followed by an optional space and the * for pointer. But in variable names, we often use underscores, so I search for those explicitly.

Now I need to save parts of the search expression and use them in the replace expression. So I enclose in \( \), and reference with \N
The search becomes:
(\(\w+ ?\*\))\([A-Za-z_]+\)

and the replace becomes:

A case this doesn't handle is if the C-style cast was on a method or function call, or array reference.
(Outline *)annot_to_save[i]

dynamic_cast<Outline *>(annot_to_save)[i]

instead of
dynamic_cast<Outline *>(annot_to_save[i])

I figured this out by reading Emacs .. Help .. Browse the Emacs Manual .. Regexps
BTW, regexp is short for regular expression, a mainstay of the Perl community, among others.
Post a Comment