triandicAnt
triandicAnt

Reputation: 1378

Regex expression to capture '*' while excluding comment section

I want to capture all the * in the code except the comment section. The regex for comment section is: (\/\*\[\S\s\]*?\*\/) I tried excluding the the comment section and search for any * character preceded/succeeded by 0 or more spaces.

Regex : [^\/\*[\S\s]*?\*\/\]\s*\*\s*


/**
 * This function is useless
 *
 * @return      sth
 */
public void testMe() {
    int x = 5*4;
    x*=7;
    x = x**2;
}

It should match all the * inside testMe.

Upvotes: 0

Views: 77

Answers (1)

wp78de
wp78de

Reputation: 18950

This can be solved using the *SKIP what's to avoid schema using capture groups, i.e. What_I_want_to_avoid|(What_I_want_to_match):

\/\*[\S\s]*?\*\/|(\*+)

The idea here is to completely disregard the overall matches returned by the regex engine: that's the trash bin. Instead, we only need to check capture group $1, which, when set, contains the asterisks outside of comments.

Demo

Upvotes: 2

Related Questions