gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 23:00:21 25 4
gpt4 key购买 nike

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

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

关于javascript - 使用 JavaScript 的正则表达式从 SQL 查询字符串中删除注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57814265/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com