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

标签 javascript regex

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

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/

相关文章:

javascript - 等待图像加载到 angularjs 工厂内

javascript - Chrome 扩展内容安全策略在设置为 * 时抛出错误

regex - 在 Go 中使用 filepath.Glob

python - python中的复杂正则表达式匹配

Python RE 在/ref= 之后不返回任何内容

Javascript/jQuery 字符串操作,将 <b> 标签包裹在所有文本的字符串周围,并在其后直接添加冒号

javascript - 在 vanilla JavaScript 中删除所有具有特定子元素(嵌套至少 2 层)的元素

javascript - Meteor "load more"按钮,带有 Iron Router,且 url 中没有 "Posts Limit"

javascript - 在复选框更改时重置 mootools 的表单检查

javascript - 如何从 json 数据中删除 并在 React 应用程序中显示纯文本