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开发者_Python百科 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 can try:
/\/\*.*?\*\//
Since there are some / in the regex, its better to use a different delimiter as:
#/\*.*?\*/#
You need to escape your backslashes before the stars.
string str = "hi /* hello */ hi";
str = Regex.Replace(str, "/\\*.*?\\*/", " ");
//str == "hi hi"
精彩评论