Olaseni
Olaseni

Reputation: 7916

Strip out C Style Multi-line Comments

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?

Upvotes: 3

Views: 2353

Answers (4)

Brian R. Bondy
Brian R. Bondy

Reputation: 347216

You need to escape your backslashes before the stars.

string str = "hi /* hello */ hi";
str = Regex.Replace(str, "/\\*.*?\\*/", " ");
//str == "hi  hi"

Upvotes: 0

jmster
jmster

Reputation: 995

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.

Upvotes: 3

codaddict
codaddict

Reputation: 455000

You can try:

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

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

#/\*.*?\*/#

Upvotes: 0

Anthony Pegram
Anthony Pegram

Reputation: 126834

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);

Upvotes: 1

Related Questions