简体   繁体   中英

Regex to remove comments from SQL Query String using JavaScript

I managed to find the regex for handling /* */ cases but it doesn't work well for -- cases. How can I change my regex to fix this?

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

Thank you

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM