tags:

views:

168

answers:

4

I have a C# string object that contains the code of a generic method, preceded by some standard C-Style multi-line comments.

I figured I could use System.Text.RegularExpressions to remove the comment block, but I can seem to be able to get it to work.

I tried:

code = Regex.Replace(code,@"/\*.*?\*/","");

Can I be pointed in the right direction?

+1  A: 

You need to escape your backslashes before the stars.

string str = "hi /* hello */ hi";
str = Regex.Replace(str, "/\\*.*?\\*/", " ");
//str == "hi  hi"
Brian R. Bondy
I used the verbatim operator @, without it, I got compile errors
Olaseni
@Olaseni: See the code example it compiles and works.
Brian R. Bondy
+1  A: 

Use a RegexOptions.Multiline option parameter.

string output = Regex.Replace(input, pattern, string.Empty, RegexOptions.Multiline);

Full example

string input = @"this is some stuff right here
    /* blah blah blah 
    blah blah blah 
    blah blah blah */ and this is more stuff
    right here.";

string pattern = @"/[*][\w\d\s]+[*]/";

string output = Regex.Replace(input, pattern, string.Empty, RegexOptions.Multiline);
Console.WriteLine(output);
Anthony Pegram
+3  A: 

You are using backslashes to escape * in the regex, but you also need to escape those backslashes in the C# string.

Thus, @"/\*.*?\*/" or "/\\*.*?\\*/"

Also, a comment should be replaced with a whitespace, not the empty string, unless you are sure about your input.

J-mster
A: 

You can try:

/\/\*.*?\*\//

Since there are some / in the regex, its better to use a different delimiter as:

#/\*.*?\*/#
codaddict