2013-03-20 41 views
0

我有一个带混合NC代码和C#代码的文本文件。 C#代码以“<#”开始,以“#>”结尾。 现在我需要一个正则表达式来查找所有NC-评论。一个问题是NC-Comments以“;”开头因此我有一些问题来区分NC评论与“;”的C#代码。正则表达式匹配混合C#字符串中的NC注释 - 代码

只有一个正则表达式可以实现吗?

; 1. NC-Comment 
FUNCT_A; 
FUNCT_B; 

<# // C#-Code 
int temp = 42; 
string var = "hello"; // C#-Comment 
#> 

FUNCT_C ; 2. Comment 

<# // C#-Code 
for(int i = 0; i <10; i++) 
{ 
    Console.WriteLine(i.ToString()); 
} 
#> 

; 3. Comment 
FUNCT_D; 

正则表达式的结果应该是{1。 NC-注释,注释2,3,评论}

我打角落找寻与以下正则表达式:

1.) (;(.*?)\r?\n) --> Finds all NC-Comments but also C#-Code as comment 
2.) (#>.*?<#)|(#>.*) --> Finds all NC-Code except the first NC-Code fragment 
3.) #>.+?(?=<#) --> Finds all NC-Code except the first and last NC-Code fragment 

一种解决方案可能是每个“<#”推到堆栈和弹出每个“ #>“。所以如果堆栈是空的,那么当前字符串是NC代码。接下来,我必须知道这个字符串是否是NC评论。

+0

为什么使用一个复杂的缓慢的正则表达式时,你可以做同样更简单,更快,无正则表达式? – 2013-03-20 19:30:06

+0

这并不那么简单。如果C#代码本身包含评论怎么办?如果您在C#注释中有'<#' or '#>',该怎么办? – 2013-03-20 19:37:55

+0

如果没有正则表达式,你会如何实现? – user1579585 2013-03-21 07:25:42

回答

1

我宁愿做没有正则表达式:

public static List<string> GetNCComments(Stream stream) 
{ 
    using (StreamReader sr = new StreamReader(stream)) 
    { 
     List<string> result = new List<string>(); 
     bool inCS = false; // are we in C# code? 
     int c; 
     while ((c = sr.Read()) != -1) 
     { 
      if (inCS) 
      { 
       switch ((char)c) 
       { 
        case '#': 
         if (sr.Peek() == '>') // end of C# block 
         { 
          sr.Read(); 
          inCS = false; 
         } 
         break; 
        case '/': 
         if (sr.Peek() == '/') // a C# comment 
          sr.ReadLine(); // skip the whole comment 
         break; 
       } 
      } 
      else 
      { 
       switch ((char)c) 
       { 
        case '<': 
         if (sr.Peek() == '#') // start of C# block 
         { 
          sr.Read(); 
          inCS = true; 
         } 
         break; 
        case ';': // NC comment 
         string comment = sr.ReadLine(); 
         if (!string.IsNullOrEmpty(comment)) 
          result.Add(comment); 
         break; 
       } 
      } 
     } 
     return result; 
    } 
} 

用法:

var comments = GetNCComments(new FileStream(filePath, FileMode.Open, FileAccess.Read)); 

的代码很简单,自我解释。这也处理C#注释,但不处理C#字符串。我的意思是,如果你在C#注释中有#>,它可以正常工作。但是,如果你有一个C#字符串(不正确地认为它是C#块的结尾)的相同的东西不起作用。处理这种情况也很容易。