正则表达式使用混合C#代码在字符串中匹配NC注释
我有一个混合了NC代码和C代码的文本文件。C#-代码以“”开头。 现在我需要一个正则表达式来查找所有NC注释。一个问题是NC注释以“;”开头,因此我在C#代码中将NC注释与“;”区分时遇到了一些问题 只有一个正则表达式可以实现这一点吗正则表达式使用混合C#代码在字符串中匹配NC注释,c#,regex,regex-lookarounds,lookbehind,negative-lookahead,C#,Regex,Regex Lookarounds,Lookbehind,Negative Lookahead,我有一个混合了NC代码和C代码的文本文件。C#-代码以“”开头。 现在我需要一个正则表达式来查找所有NC注释。一个问题是NC注释以“;”开头,因此我在C#代码中将NC注释与“;”区分时遇到了一些问题 只有一个正则表达式可以实现这一点吗 ; 1. NC-Comment FUNCT_A; FUNCT_B; <# // C#-Code int temp = 42; string var = "hello"; // C#-Comment #> FUNCT_C ; 2. Comment
; 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注释
函数A;
功能;
函数C;2.评论
查找所有NC注释,但也将C#代码作为注释查找
2.(#>.*?*)-->查找除第一个NC代码片段外的所有NC代码
3.#>.+?(?=查找除第一个和最后一个NC代码片段外的所有NC代码
一种解决方案是从堆栈中推送每个“”。因此,如果堆栈为空,则当前字符串为NC代码。接下来,我必须确定此字符串是否为NC注释。我宁愿不使用正则表达式:
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;
}
}
代码简单明了。它也可以处理C#注释,但不能处理C#字符串。我的意思是,如果在C#注释中有
,它就可以正常工作。但是如果你有相同的东西C#字符串(错误地认为它是C#块的结尾),它就不能正常工作处理这种情况也很容易。如果没有正则表达式,你可以更简单更快地完成同样的工作,为什么还要使用复杂的慢速正则表达式?这可不是那么简单。如果C代码本身包含注释呢?如果在C注释中有一个
?没有正则表达式,你将如何实现?我将在几个小时后发布一个答案。
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));