从源文件中删除所有注释(单行/多行)和空行

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)

我们可以拥有比上面这三个例子更复杂的来源.有人可以建议使用正则表达式或其他方法来解决这个问题.我已经在互联网上浏览了很多东西,并且找不到任何可行的东西.

sga*_*101 6

要删除评论,请参阅此答案.之后,删除空行是微不足道的.


Qta*_*tax 5

您可以在此答案中使用该功能:

static string StripComments(string code)
{
    var re = @"(@(?:""[^""]*"")+|""(?:[^""\n\\]+|\\.)*""|'(?:[^'\n\\]+|\\.)*')|//.*|/\*(?s:.*?)\*/";
    return Regex.Replace(code, re, "$1");
}
Run Code Online (Sandbox Code Playgroud)

然后删除空行。