Regular expression to match "select ... from ... where" sql query
6 answers
You don't have to have a backslash; since you did, the engine tries to match a literal point, not "any character" as you would expect.
Try:
SELECT\s.*FROM\s.*WHERE\s.*
Also, like the others posted, make sure to be in case insensitive mode. How you do this depends on the language you are using.
+8
source to share
I'm not sure which regex engine you are targeting, but you can try this:
# note the trailing i, which in perl means case-insensitive
# this will also put the interesting bits into regex backreferences
#
# This also changes \s to \s+ in case you have a situation with multiple
# spaces between terms
#
/select\s+(.*)\s+from\s+(.*)\s+where\s+(.*)/i
+5
source to share
Assumptions:
- Your sql statement will not span rows.
- You won't have two sql statements on the same line.
This works for me.
SELECT\s+?[^\s]+?\s+?FROM\s+?[^\s]+?\s+?WHERE.*
Java escaped version:
String regex = "SELECT\\s+?[^\\s]+?\\s+?FROM\\s+?[^\\s]+?\\s+?WHERE.*";
You can add a terminator instead. * depending on your case. Of course, you have to run it in case insensitive mode, or change the regex accordingly.
0
source to share
Thanks guys answer. I got a response from mmyers, here is my final solution:
string szPattern = @"SELECT\s.*FROM\s.*WHERE\s.*";
Regex rRegEX = new Regex ( szPattern,RegexOptions.IgnoreCase | RegexOptions.Multiline );
Match match =rRegEX.Match(testCase.Statement);
if (match.Success)
0
source to share