我设法找到用于处理/ * * /情况的正则表达式,但不适用于-情况。如何更改我的正则表达式以解决此问题?

var s = `SELECT * FROM TABLE_A
/* first line of comment
   second line of comment */
   -- remove this comment too
   SELECT * FROM TABLE_B`;

var stringWithoutComments = s.replace(/(\/\*[^*]*\*\/)|(\/\/[^*]*)|(--[^*]*)/g, '');
/*
Expected:

SELECT * FROM TABLE_A
SELECT * FROM TABLE_B
*/
console.log(stringWithoutComments);


谢谢

https://jsfiddle.net/8fuz7sxd/1/

最佳答案

var s = `SELECT * FROM TABLE_A
/* first line of comment
   second line of comment */
   -- remove this comment too
   SELECT * FROM TABLE_B`;

var stringWithoutComments = s.replace(/(\/\*[^*]*\*\/)|(\/\/[^*]*)|(--[^.].*)/gm, '');
/*
Expected:

SELECT * FROM TABLE_A
SELECT * FROM TABLE_B
*/
console.log(stringWithoutComments);

// without linebreak
stringWithoutComments = stringWithoutComments.replace(/^\s*\n/gm, "")
console.log(stringWithoutComments);


// without whitespace
stringWithoutComments = stringWithoutComments.replace(/^\s+/gm, "")
console.log(stringWithoutComments);

09-20 14:16