如何在正则表达式中表示C ++函数名?

时间:2016-10-20 17:59:50

标签: c++ regex visual-studio

我想像这样改变项目中的所有功能。

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

- >

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

以下代码是另一个例子。

void Enemy::Change()
{

}

- >

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

}

但我的项目有太多功能无法改变。所以我决定使用正则表达式来改变它的所有功能。

(Visual Studio支持通过常规表达替换代码)

但是我不熟悉正则表达式,所以我不知道它。

如何以较高的方式更改项目中的所有功能?

1 个答案:

答案 0 :(得分:3)

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.