C#Regex查找未注释的行

本文关键字:注释 查找 C#Regex | 更新日期: 2023-09-27 18:29:45

我使用((?:/''*(?:[^*]|(?:''*+[^*/]))*''*+/))|(--[^@].*['r'n]) Regex来识别文件中的所有注释。(我正在阅读一个PL/SQL文件,它使用--表示单个注释,使用/**/表示多行注释)这很好,我可以毫无问题地得到所有的评论。

我想得到与上面的正则表达式不匹配的代码。所以我用了Regex [^(((?:/''*(?:[^*]|(?:''*+[^*/]))*''*+/))|(--[^@].*['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.

我如何获得非评论的行?

C#Regex查找未注释的行

尝试使用另一种方式:

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

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

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