日期:2014-05-20  浏览次数:20621 次

求java正则:从一个select的SQL语句里获取表名
即从
select * from abc 获取abc
当然sql可能复杂多了。。比如
select a,b,c from a where id=1 order by id desc
SELECT * from a group by age

这样。求具体的java代码(对JAVA操作正则不太了解..@_@)

------解决方案--------------------
其实完全可以不用正则来解决,不过正则也快一点吧,下面是稍微粗糙的一个例子,我想应该能解决问题了
Java code

String sql="select a,b,c from abc where id=1 order by id desc";
        String regex="\\bfrom\\s*\\S*";
        Pattern p=Pattern.compile(regex);
        Matcher m=p.matcher(sql);
        if(m.find()){
            String table=m.group().replace("from","");
            System.out.println(""+table.trim());
        }else{
            System.out.println("not found");
        }

------解决方案--------------------
String str="select a,b,c from abc where id=1 order by id desc";
Pattern p=Pattern.compile("(.*from\\s)(\\w*)(.*)");
Matcher m=p.matcher(str);
if(m.find()){
System.out.println(m.group(2));
}else{
System.out.println("false");
}