Regex to capture code comments not working when *

2019-08-17 23:54发布

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

2条回答
We Are One
2楼-- · 2019-08-18 00:17

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

查看更多
【Aperson】
3楼-- · 2019-08-18 00:18
\/\*[\s\S]*?\*\/

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

查看更多
登录 后发表回答