如何修改函数的所有开头和结尾

时间:2014-08-11 09:11:39

标签: regex

我想修改以下类型的所有功能:

returnType functionName(parameters){
    OLD_LOG; // Always the first line of the function
    //stuff to do

    return result; // may not be here in case of function returning void
} // The ending } is not always at the beginning of the line (but is always the first not white space of the line and has the same number of white space before than 'returnType' does)

通过

returnType functionName(parameters){
    NEW_LOG("functionName"); // the above function name

    //stuff to do

    END_LOG();
    return result; //if any return (if possible, END_LOG() should appear just before any return, or at the end of the function if there is no return)
}

这些功能中至少有一百个。

因此,我想知道是否可以在文本编辑器中使用“查找/替换”来支持正则表达式或其他任何内容。

谢谢

3 个答案:

答案 0 :(得分:1)

这是尝试相同的

<强>正则表达式

/(?<=\s)(\w+)(?=\()(.*\{\n.*)(OLD_LOG;)(.*)(\n\})/s

测试字符串

returnType functionName(parameters){
    OLD_LOG;
    //stuff to do

}

替换字符串

\1 \2NEW_LOG("\1");\n\4\n    END_LOG();\5

<强>结果

returnType functionName (parameters){
    NEW_LOG("functionName");

    //stuff to do

    END_LOG();
}

直播demo here


我已更新正则表达式以包含可选的return语句&amp;可选空格

<强>正则表达式

/(?<=\s)(\w+)(?=\()(.*\{\n.*)(OLD_LOG;)(.*?)(?=(?:\s*)return|(?:\n\s*\}))/s

替换字符串

\1 \2NEW_LOG("\1");\n\4\n    END_LOG();

return statement

的演示

optional spaces

的演示

看看这是否适合你

答案 1 :(得分:1)

查找

(\n([^\S\n]*)[^\s].*\s([^\s\(]+)\s*\(.*\)\s*\{\s*\n)(\s*)OLD\_LOG;((.*\s*\n)*?)(\s*return\s.*\r\n)?\2\}

替换为

\1\4NEW\_LOG\(\"\3\"\);\5\4END_LOG\(\);\r\n\7\2\}

请注意,\n\r\n已被使用。如果您的代码文件使用不同的换行格式,则需要相应地进行修改。

这种替代的限制是这些假设:

1)OLD_LOG;只是函数名称下面的一行。

2)函数有返回类型(函数名称正常之前的任何非空格字符)。

3)功能名称和{在同一行。

4)结尾}与“returnType”之前的空白数量相同,并且函数内部没有}

5)最后return只是结尾}上方的一行。

答案 2 :(得分:0)

使用支持多个插入符号的编辑器可能会更快(例如 Sublime Text IntelliJ ):

enter image description here