Regular expression needed to remove C / C # comments

I need a C # regex to remove everything between /* and */ , including /**/ . So basically delete all the code comments in this text.

+6
source share
3 answers

There should be something like this:

 var regex = new Regex("/\*((?!\*/).)*\*/", RegexOptions.Singleline); regex.Replace(input, ""); 
+6
source

Be careful that comments can be nested. If comments can be nested, like in SQL, the main regex will look like this:

 /\*.*?\*/ 

You will need a loop until you lose nothing.

If, on the contrary, comments end in the first * /, as in C, you need to be greedy with a negative look:

 /\*((?!\*/).)*\*/ 
+2
source

I also needed to ignore line comments using the form

 // blablabla 

So, simply, if someone needs it, change the regex by adding the last part | (//.*) , so the full form will be:

 (/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)|(//.*) 
0
source

Source: https://habr.com/ru/post/889110/


All Articles