Click here to Skip to main content
15,891,567 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, i want to delete rows which has comments like "//" or "/*...*/" multile line or single line in C#

what i did is,

C#
static string StripComments(string code)
 { var re = @"(^\/\/.*?$)|(\/*.*?*\/)";
 return Regex.Replace(code, re, "$1");
 }

In a Class
string s="/*#define abcdef
            #define ghijkl*/;
             

 while (s.Contains("#define"))
 {s= StripComments(s);}


is it correct what i did? thanks
Posted
Updated 6-Jun-13 4:37am
v2
Comments
E.F. Nijboer 6-Jun-13 10:10am    
create test cases and specify the result you expect and then perform those test accordingly and verify.
johannesnestler 6-Jun-13 10:37am    
good advice!
Ahmed Bensaid 6-Jun-13 10:49am    
Maciej Los 6-Jun-13 10:56am    
Please, post it as an answer ;)
Ahmed Bensaid 6-Jun-13 11:00am    
Done ;)

You can only detect comments in a robust way if you do properly tokenize into
- tokens that can contain comment start/end character sequences (all flawours of strings, characters)
- tokens that cannot contain comment start/end character sequences (all but the above tokens and but comments)
- line comments
- block comments

You may have a look at Escaping in C#: characters, strings, string formats, keywords, identifiers[^] at the bottom, see the bonus code for tokenizing C# with Regex, including line and block comments, taking in care of the above mentioned tokens.

Cheers
Andi
 
Share this answer
 
Comments
Maciej Los 6-Jun-13 11:02am    
Well explained.
+5
Andreas Gieriet 6-Jun-13 11:26am    
Thanks for your 5!
Cheers
Andi
Have a look there : Regex to strip line comments from C# ;)
 
Share this answer
 
Comments
Maciej Los 6-Jun-13 11:02am    
+5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900