/** *本文用到了正则表达式,如果你对正则表达式不熟悉,请查看相应的资料,jdk1.4以上支持正则表达式,具体可以 *参考java.util.regexp.Pattern里的javadoc(讲的还不错) *最初发布的时候很仓促,一行注释都没有,实在对不住各位了. *这个小程序是用来检测sql(select)语句是否合法的,其实主要目的是探讨怎么用正则表达式来表示sql语句. *由于sql里包含了函数和子查询,这都属于语法分析的范畴,而正则表达式是用来表示词法的,要实现这一点好像比较吃力(lex好像也难), *所以我决定不再努力去实现这个目标(另外写语法分析程序吧). *@author [email protected] */ import java.util.*; import java.text.*; class sqltest {  public static void main(String[] args)   {   String span="select aaaa.id   name ,hello ,type t,h from datas aaaa,city b  where a.id=b.id and c like 'e%'  and name is null ";   span=span.toUpperCase();//测试用sql语句   System.out.println(span);   String column="(\\w+\\s*(\\w+\\s*){0,1})";//一列的正则表达式 匹配如 product p   String columns=column+"(,\\s*"+column+")*"; //多列正则表达式 匹配如 product p,category c,warehouse w   String ownerenable="((\\w+\\.){0,1}\\w+\\s*(\\w+\\s*){0,1})";//一列的正则表达式 匹配如 a.product p   String ownerenables=ownerenable+"(,\\s*"+ownerenable+")*";//多列正则表达式 匹配如 a.product p,a.category c,b.warehouse w 
  String from="FROM\\s+"+columns;   String condition="(\\w+\\.){0,1}\\w+\\s*(=|LIKE|IS)\\s*'?(\\w+\\.){0,1}[\\w%]+'?";//条件的正则表达式 匹配如 a=b 或 a is b..   String conditions=condition+"(\\s+(AND|OR)\\s*"+condition+"\\s*)*";//多个条件 匹配如 a=b and c like 'r%' or d is null    String where="(WHERE\\s+"+conditions+"){0,1}";   String pattern="SELECT\\s+(\\*|"+ownerenables+"\\s+"+from+")\\s+"+where+"\\s*"; //匹配最终sql的正则表达式   System.out.println(pattern);//输出正则表达式   System.out.println(span.matches(pattern));//是否比配 
  }  } 
  
   
 
  |