I need to write a regex expression for validating if a sql query in the form of a string begins with a SELECT and ends with a LIMIT followed by a number. Of course, this needs to be case insensitive and should be able to ignore preceding and trailing whitespaces.
Valid String:
1. select * from table where col='anything' limit 10
2. SELECT * from table where col='anything' LIMIT 10
Invalid String:
1. select * from table where col='anything'
2. SELECT * from table where col='anything'
I have tried the following, but it is not matching for any case and printing false for all four cases:
public class Main {
private static final String regex = "^SELECT(?:[^;']|(?:'[^']+'))+ LIMIT + \\d+;\\s*$";
private static final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE | Pattern.CASE_INSENSITIVE);
private static boolean matchesPattern(String query) {
return pattern.matcher(query).matches();
}
public static void main(String[] args) {
String[] queries = {
"select * from table where col='anything'", // should print false, as no limit condition
"select * from table where col='anything' limit 10", // should print true
"SELECT * from table where col='anything'", // should print false, as no limit condition
"SELECT * from table where col='anything' LIMIT 10" // should print true
};
for (String query: queries){
System.out.println(matchesPattern(query));
}
}
}
'be escaped in the '...' string? BTW, you just need to make;optional and remove the space before\\d+:^SELECT(?:[^;']|(?:'[^']+'))+ LIMIT +\d+;?\s*$.