doctopus
doctopus

Reputation: 5657

Regex to capture code comments not working when * followed by /

I've made a regex expression to capture code comments which seems to be working except in the case when the comments contains * [anynumber of characters inbetween] /, e.g.:

/* these are some comments =412414515/ * somecharacters /][;';'] */

Regex: (\/\*[^*]*[^/]*\*\/)

https://regex101.com/r/xmpTzw/2

Upvotes: 0

Views: 56

Answers (2)

wp78de
wp78de

Reputation: 18970

For a start, I suggest this pattern:

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

Demo

const regex = /(\/\*[\S\s]*?\*\/)/g;
const str = `This is/ some code /* these are some comments
=412414515/  * somechars /  ][;';'] */*/
Some more code 
/* and some more unreadable comments a[dpas[;[];135///]] 
d0gewt0qkgekg;l''\\////
*/ god i hate regex  /* asda*asd
\\asd*sd */`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

Upvotes: 2

David Hayes
David Hayes

Reputation: 196

\/\*[\s\S]*?\*\/

Just use a lazy operator instead of trying to not match *

Upvotes: 4

Related Questions