您的两个正则表达式(用于块和行注释)均存在错误。如果您愿意,我可以描述一下这些bug,但是我觉得如果编写新的bug可能会更有效率,尤其是因为我打算编写一个同时匹配两者的bug。
问题是,每次你有时间
";var lineComments = @"//(.*?)r?n";var strings = @"""((\[^n]|[^""n])*)""";var verbatimStrings = @"@(""[^""]*"")+";要回答标题中的问题(带状注释),我们需要:
- 用任何内容替换块注释
- 用换行符替换行注释(因为正则表达式会吃掉换行符)
- 将原义字符串保留在原处。
Regex.Replace可以使用Matchevaluator函数轻松做到这一点:
string noComments = Regex.Replace(input, blockComments + "|" + lineComments + "|" + strings + "|" + verbatimStrings, me => { if (me.Value.StartsWith("/*") || me.Value.StartsWith("//")) return me.Value.StartsWith("//") ? Environment.newline : ""; // Keep the literal strings return me.Value; }, RegexOptions.Singleline);我在Holystream提供的所有示例以及我能想到的其他各种情况下运行了这段代码,它的工作原理很吸引人。如果您可以提供一个失败的示例,我们很乐意为您调整代码。



