删除C样式多行注释

时间:2010-03-29 13:43:40

标签: c# regex comments

我有一个C#字符串对象,其中包含泛型方法的代码,前面是一些标准的C-Style多行注释。

我想我可以使用System.Text.RegularExpressions删除评论区块,但我似乎能够让它发挥作用。

我试过了:

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

我可以指向正确的方向吗?

4 个答案:

答案 0 :(得分:3)

您正在使用反斜杠来转义正则表达式中的*,但您还需要在C#字符串中转义那些反斜杠。

因此,@"/\*.*?\*/""/\\*.*?\\*/"

此外,注释应替换为空格,而不是空字符串,除非您确定输入。

答案 1 :(得分:2)

使用RegexOptions.Multiline选项参数。

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

完整示例

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

答案 2 :(得分:0)

你需要在星星之前逃避你的反斜杠。

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

答案 3 :(得分:0)

您可以尝试:

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

由于正则表达式中有一些/,因此最好使用不同的分隔符:

#/\*.*?\*/#
相关问题