我无法使用正则表达式检测 C# 代码中的 SQL。
这是我的正则表达式字符串:
(?i)(?s)\b(select)\b(.*?)\b(from)\b|\b(insert)\b(.*?)\b(into)\b|\b(update)\b(.*?)\b(set)\b|\b(delete)(.*?)\b(from)\b
我想像下面这样匹配 SQL 关键字:
... SELECT ... FROM ...
... INSERT ... INTO ...
... UPDATE ... SET ...
... DELETE ... FROM ...
我正在使用以下网站来测试我的正则表达式:
它的工作方式与我希望它在网站上的工作方式一样,但由于某些随机原因,如果我的代码运行,此正则表达式将不起作用。
“Regex.Matches”由于某种原因没有找到任何匹配项。
SQL 可以全部在一行中,也可以跨越多行。
所以,基本上,我为我的应用程序提供了一个目录。此目录包含“.cs”文件。
然后我读取文件中的文本,并尝试匹配上面的 Regex 字符串。
这是我目前的代码:
private string _strRegex = "(?i)(?s)\b(select)\b(.*?)\b(from)\b|\b(insert)\b(.*?)\b(into)\b|\b(update)\b(.*?)\b(set)\b|\b(delete)(.*?)\b(from)\b";
string lines = string.Empty;
bool foundMatch = false;
//Match the text to our regular expression, and see if we find a match anywhere.
foreach (Match match in Regex.Matches(strFile, _strRegex))
{
//Get the line number this match occurred at in the file.
var lineNumber = strFile.Take(match.Index).Count(c => c == '\n') + 1;
//Get the actual line.
int lineNum = 0;
using (StringReader reader = new StringReader(strFile))
{
string line;
while ((line = reader.ReadLine()) != null)
{
lineNum++; //First, increment!
if (lineNum == lineNumber)
{
line = line.Trim();
if (!line.StartsWith("//"))
{
foundMatch = true;
lines += $@" [Line {lineNumber}] - {line}{Environment.NewLine}";
break;
}
}
}
}
}
if (foundMatch)
{
File.AppendAllText(_itemsLogPath, $@"{file}{Environment.NewLine}{lines}{Environment.NewLine}");
}
请您参考如下方法:
问题是\b 正在尝试转换为 c# 字符串快捷方式,而不是正则表达式代码,您需要将字符串字面化。
private string _strRegex = @"(?i)(?s)\b(select)\b(.*?)\b(from)\b|\b(insert)\b(.*?)\b(into)\b|\b(update)\b(.*?)\b(set)\b|\b(delete)(.*?)\b(from)\b";
那个可怜的小@让一切变得不同
