using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"([""'])\s*(SELECT)(?:\s+(?:(?!\1).)*)?\s+(FROM)(?:\s+(?:(?!\1).)*)?\1(?:[^\w]|$)";
string input = @" SELECT * FROM tbl -- no match - not in a string
""SELECT * FROM tbl"" -- matches - in a double-quoted string
'SELECT * FROM tbl;' -- matches - in a single-quoted string
'SELECT * FROM it's -- no match - letter after end quote
""SELECT * FROM tbl' -- no match - quotation marks don't match
'SELECT * FROM tbl"" -- no match - quotation marks don't match
""select * from tbl"" -- no match - keywords not upper case
'Select * From tbl' -- no match - still not all upper case
""SELECT col1 FROM"" -- matches - even though no table name
' SELECT col1 FROM ' -- matches - as above with more whitespace
'SELECT col1, col2 FROM' -- matches - with multiple columns
""SELECT 'c' FROM 'tbl'"" -- matches - with identifier names quoted
""SELECT ""c"" FROM"" -- no match - same quotation marks for identifier
""SELECT * FROM"" ""quoted"" -- matches - with another unmatched quoted string
";
RegexOptions options = RegexOptions.Multiline;
foreach (Match m in Regex.Matches(input, pattern, options))
{
Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
}
}
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for C#, please visit: https://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex(v=vs.110).aspx