我觉得想拉这个时候你会发现too many edge cases用正则表达式关闭。处理报价是真正使事情复杂化的原因,更不用说转义字符了。
程序性解决方案并不复杂,并且根据需要更快更容易修改。请注意,我不知道转义字符应该是在你的榜样是什么,但你肯定会添加到算法...
string CodeSnippet = Resource1.CodeSnippet;
StringBuilder CleanCodeSnippet = new StringBuilder();
bool InsideQuotes = false;
bool InsideComment = false;
Console.WriteLine("BEFORE");
Console.WriteLine(CodeSnippet);
Console.WriteLine("");
for (int i = 0; i < CodeSnippet.Length; i++)
{
switch(CodeSnippet[i])
{
case '"' :
if (!InsideComment) InsideQuotes = !InsideQuotes;
break;
case '#' :
if (!InsideQuotes) InsideComment = true;
break;
case '\n' :
InsideComment = false;
break;
}
if (!InsideComment)
{
CleanCodeSnippet.Append(CodeSnippet[i]);
}
}
Console.WriteLine("AFTER");
Console.WriteLine(CleanCodeSnippet.ToString());
Console.WriteLine("");
这个例子条从CodeSnippet
的意见了。我以为这就是你以后的样子。
下面是输出:
BEFORE
"\#" TEST #comment hello world
"ab" TEST #comment hello world
"ab" TEST #comment "hello world
"ab" + "ca" + TEST #comment
"\#" TEST
"ab" TEST
AFTER
"\#" TEST
"ab" TEST
"ab" TEST
"ab" + "ca" + TEST
"\#" TEST
"ab" TEST
正如我所说的,你可能需要转义字符添加到该算法。但这是一个很好的起点。
你必须解析整个字符串,字符转义和所有...仅供参考,它比它看起来更难**。 – Mehrdad
想象一下''\#“测试#”测试#评论hello world“ - 大概是从第二个'#'开始的评论 - 但你怎么区分? –
@Damien - 评论开始于第三个#实际上。区分它的方法是评论总是在最后,因此从右到左解析它直到碰到第一个#是我的目标 – Icemanind