猿问

使用 JavaScript 从 SQL 查询字符串中删除注释的正则表达式

我设法找到了用于处理 /* */ 案例的正则表达式,但它不适用于 -- 案例。如何更改我的正则表达式来解决这个问题?


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/


MMTTMM
浏览 249回答 1
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_ASELECT * FROM TABLE_B*/console.log(stringWithoutComments);// without linebreakstringWithoutComments = stringWithoutComments.replace(/^\s*\n/gm, "")console.log(stringWithoutComments);// without whitespacestringWithoutComments = stringWithoutComments.replace(/^\s+/gm, "")console.log(stringWithoutComments);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答