2

I'm trying to find a regex which can be used to match SQL style comments. Single line comments was fairly easy --.* however I can't work out how to match multi line comments. I don't need the actual replacement code just the regex to match the comments.

For instance:

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*/

Should become:

 select * from valid_sql1;

 select * from valid_sql2;

 select * from valid_sql3;

Any help is greatly appreciated.

Qix - MONICA WAS MISTREATED
  • 14,451
  • 16
  • 82
  • 145
John Walker
  • 291
  • 1
  • 5
  • 16

3 Answers3

5

With global modifier if your Regex engine accepts:

/\/\*.*?\*\/|--.*?\n/gs

s modifier is needed for multi-line comments matching.

Demo

Community
  • 1
  • 1
revo
  • 47,783
  • 14
  • 74
  • 117
  • Thanks, demo was very helpful, modified slightly to work in java replaceAll \\/\\*[\\s\\S]*?\\*\\/ – John Walker Jan 09 '14 at 11:13
  • Nice. One warning though: it doesn't match a comment at end of file with no linebreak, so it's worth appending a linebreak to the script first to avoid having to treat EOF any differently. To use this in .Net, the syntax I ended up with is: `string scriptWithoutComments = Regex.Replace(script + "\n", @"\/\*.*?\*\/|--.*?\n", "", RegexOptions.Singleline);` – Reg Edit Jun 04 '14 at 16:55
  • It will match comment-like blocks that are inside text. – vitaly-t Sep 14 '17 at 00:01
1

Regular Expression:

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

Replacement Text:

Empty space.


That will remove the comments for you. You will have to match the entire file, not line-by-line.

Vasili Syrakis
  • 9,321
  • 1
  • 39
  • 56
1

How to ignore the comment in SQL string.

--comment1

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

/*
*
*/

/*  */

/**/
mokeyish
  • 1
  • 1