当*后跟/时,正则表达式捕获代码注释不起作用

时间:2017-12-06 02:48:14

标签: javascript regex

我已经制作了一个正则表达式来捕获代码注释,这些注释似乎有效,除非注释包含* [anynumber of characters inbetween] /,例如:

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

正则表达式:(\/\*[^*]*[^/]*\*\/)

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

2 个答案:

答案 0 :(得分:4)

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

只使用惰性运算符而不是尝试不匹配*

答案 1 :(得分:2)

首先,我建议这种模式:

(\/\*[\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}`);
    });
}