Search code examples
regexvim

using regex to replace unknown text


Say I have the following code

int func1(int a);
int func2(int a);
int func3(int a);

Using vim search and replace, I want to turn it into this

/* This function handles action 1*/
int func1(int a);
/* This function handles action 2 */
int func2(int a);
/* This function handles action 3 */
int func2(int a);

To search for each function is simple enough, I can simply do this /int func. But, I don't know how I can use the value of the . in the replace section. How can this be accomplished?


Solution

  • You would use what is colloquially called "capture groups" (though Vim doesn't really have a name for that mechanism).

    In Vim, you define a capture group by wrapping what you want to capture with escaped parentheses:

    :%s/foo\(what you want to capture\)bar/what you want to capturebaz
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    

    and you use it with an escaped number in the range 1-9 corresponding to the position of the capture group in the pattern:

    :%s/foo\(what you want to capture\)bar/\1baz
                                           ^^
    

    See :h \(.

    In this specific case:

    :%s/int func\(.\)/\/* This function handles action \1 *\/\r\0
    

    where we even use \0 which references the whole pattern.