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;

becomes
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:
dynamic_cast<\1>(\2)


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

became
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.

Comments

Popular posts from this blog

Inno Setup custom data directory location

OpenEmbedded Angstrom for Advantech PCM-9375

Inno Setup MSVC vcredist without bothering your users