Home > Software engineering >  How to avoid matching unwanted blocks in regex
How to avoid matching unwanted blocks in regex

Time:02-04

How to avoid matching unwanted blocks in regex.

For example, I just want to match the static prototypes in C language and how to make it not include the main function.

/**
 * @brief
 *
 * @param dsc
 */
static void func1(const char *dsc);

/**
 * @brief
 *
 * @param argc
 * @param argv
 * @return int
 */
int main(int argc, char *argv[]);

/**
 * @brief
 *
 * @param dsc
 */
static void fun2(const char *dsc);

my regex is

\/\*[\w\W]*?\*\/\n ^static.*\);

and it alway match the main function prototypes. In Vscode just like this:

example

CodePudding user response:

You can use

/\*(?:(?!/\*|\*/)[\w\W])*?\*/\n static.*\);

Note that you do not need to escape the / char in the search and replace field since the regex is defined with a mere string, not a regex literal notation where / chars are used as regex delimiters.

The (?:(?!/\*|\*/)[\w\W])*? part makes it match any char, zero or more but as few as possible times, that does not start a /* or */ char sequence.

You do not need ^ as a start of a line anchor here since it makes no sense after \n , it is implied there.

  • Related