正则表达式找到sql注释

时间:2014-01-09 10:06:44

标签: regex

我正在尝试找到一个可用于匹配SQL样式注释的正则表达式。单行注释相当容易 - 。*但是我无法弄清楚如何匹配多行注释。我不需要实际的替换代码只是正则表达式来匹配评论。

例如:

select * from valid_sql1;

select * from valid_sql2; --comment here

--comment select * from this_is_still_a_comment;

 /*
 select * from this_is_not_valid;
 */

 /*comment*/ select * from valid_sql3; /*this is a comment*/

应该成为:

 select * from valid_sql1;

 select * from valid_sql2;

 select * from valid_sql3;

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:3)

如果你的Regex引擎接受:{/ p>,使用g lobal修饰符

/\/\*.*?\*\/|--.*?\n/gs
多行评论匹配需要

s修饰符。

Demo

答案 1 :(得分:1)

正则表达式:

(?s)/\*.*?\*/|--comment[^\r\n]*

替换文字:

空地。


这将删除您的评论。您必须匹配整个文件,而不是逐行匹配。

答案 2 :(得分:1)

如何忽略SQL字符串中的注释。

--comment1

select *  from /*my table*/sample where a = 's -- string'
and c = 'ss/**/ /* */ 
 /*123*/'

/*
*
*/

/*  */

/**/
相关问题