nen*_*ito 12 c# regex comments
如何从C#源文件中删除所有注释和空行.请记住,可能存在嵌套注释.一些例子:
string text = @"//not a comment"; // a comment
/* multiline
comment */ string newText = "/*not a comment*/"; // a comment
/* multiline // not a comment
/* comment */ string anotherText = "/* not a comment */ // some text here\"// not a comment"; // a comment
Run Code Online (Sandbox Code Playgroud)
我们可以拥有比上面这三个例子更复杂的来源.有人可以建议使用正则表达式或其他方法来解决这个问题.我已经在互联网上浏览了很多东西,并且找不到任何可行的东西.
您可以在此答案中使用该功能:
static string StripComments(string code)
{
var re = @"(@(?:""[^""]*"")+|""(?:[^""\n\\]+|\\.)*""|'(?:[^'\n\\]+|\\.)*')|//.*|/\*(?s:.*?)\*/";
return Regex.Replace(code, re, "$1");
}
Run Code Online (Sandbox Code Playgroud)
然后删除空行。