jong-hyun Yeo jong-hyun Yeo - 1 month ago 5
C++ Question

How to represent C++ function name in regular expression?

I want to change all the function in the project like this.

void Enemy::Create(int asdf, int asdf, float asdf)
{
}


->

void Enemy::Create(int asdf, int asdf, float asdf)
{CCLOG("ERROR OCCURED");
}


And following code is another example.

void Enemy::Change()
{

}


->

void Enemy::Change()
{CCLOG("ERROR OCCURED");

}


But my project have too many function to change like it. So I decided to use regular expression to change all the function like it.

(Visual Studio support replace code by regular expresion)

But I'm not familiar with regular expression, so I have no idea for it.

How can I change all the function in the project in upper way?

Answer

Instead of just giving you a cryptic expression, I'll go into detail the process of coming up with it as well.

Much like a compiler parses code, you can compose a regular expression based on a sequence of tokens (which creates a rule). Because we're only particularly interested in the detection of a method definition, you can treat the list of arguments as anything between parameters.

You can think of it something like this -

void Enemy::Create(int asdf, int asdf, float asdf) {

Generalized as

<Identifier><Whitespace><Identifier>::<Identifier>(<Anthing>)<Whitespace>{

In C++ an identifier is _ or A-Z followed by zero or more _, A-Z or 0-9. With that said -

<Identifier> = [a-zA-Z_][a-zA-Z0-9_]*
<Whitespace> = [\n\r\s]+
  <Anything> = .*

So the expression should look something like this

([a-zA-Z_][a-zA-Z0-9_]*) # <Identifier> ($1)
([\n\r\s]+)              # <Whitespace> ($2)
([a-zA-Z_][a-zA-Z0-9_]*) # <Identifier> ($3)
::                       # ::         
([a-zA-Z_][a-zA-Z0-9_]*) # <Identifier> ($4)
\(                       # (
(.*)                     # <Anything>   ($5)
\)                       # )
([\n\r\s]+)              # <Whitespace> ($6)
\{                       # {

But Visual Studio doesn't support multi-line find stuff so use this

([a-zA-Z_][a-zA-Z0-9_]*)([\n\r\s]+)([a-zA-Z_][a-zA-Z0-9_]*)::([a-zA-Z_][a-zA-Z0-9_]*)\((.*)\)([\n\r\s]+)\{

And for the replacement, you'll have to reconstruct the expression with the capture groups listed above. Here's where you'll insert your CCLOG.

$1$2$3::$4($5)\n{CCLOG("ERROR OCCURED"); 

Note that this is pretty gross and only should be used for something quick and dirty like refactoring your code in Visual Studio. It won't handle other cases like constructor initialization lists, throw, const, noexcept, etc. But you can use the same concepts to write an expression to handle it.