简体   繁体   中英

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?

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.

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

You need to escape your backslashes before the stars.

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

You can try:

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

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

#/\*.*?\*/#

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM