求java正则:从一个select的SQL语句里获取表名

我不是稻草人 2012-08-04 03:07:47
即从
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操作正则不太了解..@_@)
...全文
1109 2 打赏 收藏 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
wwwcomcn123 2012-08-04
  • 打赏
  • 举报
回复
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");
}
风尘中国 2012-08-04
  • 打赏
  • 举报
回复
其实完全可以不用正则来解决,不过正则也快一点吧,下面是稍微粗糙的一个例子,我想应该能解决问题了

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");
}

62,620

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧