azerty
azerty

Reputation: 777

How to Modify all beginnings and endings of a function

I would like to modify all the function which are of the following kind:

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)

by

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)
}

There is a at least a hundred of those functions.

Therefore I would like to know if it is possible to do that using a "look for/replace" in a text editor supporting regex for exemple, or anything else.

Thank you

Upvotes: 0

Views: 74

Answers (3)

cshu
cshu

Reputation: 5954

Find

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

Replace with

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

Notice that \n and \r\n are used. If your code file uses a different newline format, you need to modify accordingly.

Limitations of this replace are these assumptions:

1) OLD_LOG; is just one line below the function name.

2) Function has return type (any non space character before the function name is okay).

3) Function name and { are at the same line.

4) Ending } has the same number of white space before than 'returnType' does, and there is no such } inside the function.

5) Last return is just one line above the ending }.

Upvotes: 1

pushpraj
pushpraj

Reputation: 13679

here is an attempt for the same

Regex

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

Test String

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

}

Replace string

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

Result

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

    //stuff to do

    END_LOG();
}

live demo here


I have updated the regex to include optional return statement & optional spaces

Regex

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

Replace string

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

demo for return statement

demo for optional spaces

see if this works for you

Upvotes: 1

&#201;douard Lopez
&#201;douard Lopez

Reputation: 43419

It may be faster to use an editor with multiple carets support (e.g. Sublime Text, IntelliJ):

enter image description here

Upvotes: 0

Related Questions