【Java/Regexp】用正则表达式验证sql是否select语句
需求:
输入sql,判断其是否查询语句,检查规则是:select开头,sql中不允许有insert、delete和update的出现。
程序:
package test; public class SelectMatch { public static void main(String[] args) { String[] arr= { "select * from dual", " Select f1,f2 from tb", "select * from tb for update", "insert into tb value(1,2)", " update tb set f1=1 where f2=2", " delete from tb where id=10", " SELET a,b,c from tb where d=5", "SELect a.*,b.* from a left join b on a.id=b.aid", " select A from B | delete", " selectsysdate from dual", " select insert from tb",}; for(String text:arr) { if(isSelect(text)) { System.out.println(text); } } } private static boolean isSelect(String sql) { return sql.matches("^(?i)(\\s*)(select)(\\s+)(((?!(insert|delete|update)).)+)$"); } }
输出:
select * from dual Select f1,f2 from tb SELect a.*,b.* from a left join b on a.id=b.aid
正则表达式分析:
^...$ :将目标字符串从头检查到尾,毋庸多言;
(?i):不区分大小写
(\\s*):select之前允许有0个或多个空格
(select):空格或开头后就必须有select
(\\s+): select之后必须跟至少一个空格
(?!(insert|delete|update)). :上面的空格后的任意字符,前方不得有insert、delete、update之一
((?!(insert|delete|update)).)+ :“任意字符,前方不得有insert、delete、update之一”这个模式,可以重复一到多次。
END
PS:如果对?!正则式陌生,可以参考:https://www.cnblogs.com/heyang78/p/15720928.html