【问题标题】:C# Regex find line that are not commentedC# Regex 查找未注释的行
【发布时间】:2015-01-06 07:56:31
【问题描述】:

我正在使用((?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/))|(--[^@].*[\r\n]) Regex 来识别文件中的所有 cmets。 (我正在读取一个 PL/SQL 文件,它使用 -- 用于单个 cmets 和 /* */ 用于多行 cmets) 这很好用,我可以毫无问题地获得所有 cmets。

我想获取与上述正则表达式不匹配的代码。 所以我使用了正则表达式[^(((?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/))|(--[^@].*[\r\n]))]

 MatchCollection matches = Regex.Matches(text, "[^(((?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/))|(--[^@].*[\r\n])])");
 for (int i = 0; i < matches.Count; i++)
 {
      Console.WriteLine(matches[i].Groups[0].Value);
 }

然后当我尝试运行它时说

The file could not be read:
parsing "[^((?:/\*(?:[^*]|(?:\*+[^*/]))*\*+/))|(--[^@].*[
])]" - Too many )'s.

如何获取非 cmets 的行?

【问题讨论】:

  • [^...] 是一个字符类。它不会将内容识别为字符类或内部字符以外的任何内容。
  • @nhahtdh 如果是这样,我还有其他方法可以匹配非注释代码吗?
  • 我希望你的 SQL 不包含 SELECT 'some -- string' FROM [some--table] ;-)
  • @LucasTrzesniewski PLSQL 文件不仅仅是 sql 查询

标签: c# regex comments


【解决方案1】:

我能够删除 cmets 并获得未注释的文本,如下所示

public static readonly string BLOCK_COMMENTS = @"/\*(.*?)\*/";
public static readonly string LINE_COMMENTS  = @"--[^@](.*?)\r?\n";
public static readonly string STRINGS        = @"""((\\[^\n]|[^""\n])*)""";

string sWithoutComments = Regex.Replace(textWithComments.Replace("'", "\""), ServerConstant.BLOCK_COMMENTS + "|" + ServerConstant.LINE_COMMENTS + "|" + ServerConstant.STRINGS,
                me =>
                {
                    if (me.Value.StartsWith("/*") || me.Value.StartsWith("--"))
                        return me.Value.StartsWith("--") ? Environment.NewLine : "";
                    return me.Value;
                },
                RegexOptions.Singleline);

【讨论】:

    【解决方案2】:

    用另一种方式试试:

    MatchCollection matches = Regex.Matches(text, "((?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/))|(--[^@].*[\r\n])");
    string result=text;
     for (int i = 0; i < matches.Count; i++)
     {
         result=result.Replace(matches[i].Value);
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-27
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-11
      • 2021-06-07
      • 2014-10-15
      相关资源
      最近更新 更多