I am failing to detect SQL in C# code by using Regex.
This is my regex string:
(?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
I want to match SQL keywords like the following:
... SELECT ... FROM ...
... INSERT ... INTO ...
... UPDATE ... SET ...
... DELETE ... FROM ...
I am using the following website to test my regular expressions:
It works just like I expect it to work on the website, but for some random reason, this regex does not work if my code runs.
"Regex.Matches" does not find any matches for some reason.
The SQL can all be in one single line, or the SQL can stretch over multiple lines.
So, basically, I am giving my application a directory. This directory contains ".cs" files.
I then read the text in the files, and try to match the above Regex string.
Here is the code I have so far:
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}");
}
selectfrom the first is matched with thefromin the second.