【问题标题】:Strip out C Style Multi-line Comments去掉 C 风格的多行注释
【发布时间】:2011-02-02 01:20:31
【问题描述】:

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

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

我试过了:

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

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

【问题讨论】:

  • +1 以聪明的方式提出问题

标签: c# regex comments


【解决方案1】:

你需要在星星之前转义你的反斜杠。

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

【讨论】:

  • 我使用了逐字运算符@,没有它,我得到了编译错误
【解决方案2】:

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

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

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

【讨论】:

    【解决方案3】:

    你可以试试:

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

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

    #/\*.*?\*/#
    

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        猜你喜欢
        • 2011-11-15
        • 2010-12-17
        • 2012-10-12
        • 2015-11-18
        • 2018-09-06
        • 2012-02-11
        • 2014-05-08
        • 2010-10-26
        相关资源
        最近更新 更多