各位好,
我现在有一个字符串: sql= "select a as 姓名 , b 性别,c as 年龄, d from t_table"
我现在想用java代码,把姓名,性别,年龄,d
这4个字段从那个字符串中取出来,请问如何做效率高点?谢谢!
我现在有一个字符串: sql= "select a as 姓名 , b 性别,c as 年龄, d from t_table"
我现在想用java代码,把姓名,性别,年龄,d
这4个字段从那个字符串中取出来,请问如何做效率高点?谢谢!
解决方案 »
- 请教一下关于 tls 协商报错的问题
- 如何求两个int型的最大值
- 求javax.media包
- 刚刚写了一个模拟红绿灯的JAVA程序,有点小问题,请各位指教!
- 各位老师能不能写一个<html:errors>的带name和property的例子
- 关于一个包编译和执行的问题,在线等!
- 在哪儿有Effective Java这本书的电子版下?中英文都可以
- 紧急求助!!!!在java中调用c编写的exe文件时,如何让c的运行界面不出现?
- 100求解,发到[email protected]
- 如何来停止一个等待接收客户端数据的线程;
- jface 界面关闭后程序没有退出
- StringBuffer转成String类型输出有优势吗
你是要在sql这个字符串里取出什么
还是说你要从这个请求返回的RecordSet里面找出这几个字段的值?
我想找个好点的算法,效率高,不想一步步全用substring去做。
Pattern p=Pattern.compile("姓名|性别|年龄|d");
Matcher m=p.matcher(str);
while(m.find()){
System.out.println(m.group());
}
这样不行的,我这里的sql只是做个样子,实际上这个sql是动态生成的,我现在就要取出里面的字段名,不能
Pattern p=Pattern.compile("姓名|性别|年龄|d");
因为你不知道 姓名|性别|年龄|d 这些内容,你现在只知道这是个sql语句,他会有select ... from ...这样的结构。
吧情况再说具体一点,比如说select里面有多少项?都会被as么?
public class Tests {
public static void main(String[] args){
String s= "select a as 姓名 , b 性别,c as 年龄 ,d from t_table";
String su=s.toUpperCase().trim();
int a=su.indexOf("SELECT");
su=su.substring(a+6).trim();
int b=su.indexOf("FROM");
su=su.substring(0, b-4);
System.out.println("第一次取出:"+su);
String[] k=su.split(",");
String t="";
for(int i=0;i<k.length;i++){
t=k[i].trim();
System.out.println(t);
}
}
}
上述可以输出
A AS 姓名
B 性别
C AS 年龄
D但我想输出:
姓名
性别
年龄
D请问怎么做?
Pattern p=Pattern.compile(" (.+?) as (.+?)(,|from){1}?| (.+?)(,|from){1}?");
Matcher m=p.matcher(str);
while(m.find()){
if (m.group(2) != null)System.out.println(m.group(2));
if (m.group(4) != null)System.out.println(m.group(4));
}
得保证每个字段名要用,加空格隔开
public static void main(String[] args){
String s= "select c, a as 姓名 , b 性别,c as 年龄 ,d from t_table";
// String s= "select a as 姓名 from t_table";
String su=s.toUpperCase().trim();
int a=su.indexOf("SELECT");
su=su.substring(a+6).trim();
int b=su.indexOf("FROM");
su=su.substring(0, b-4);
System.out.println("第一次:"+su);
String[] k=su.split(",");
String t="";
for(int i=0;i<k.length;i++){
t=k[i].trim();
// System.out.println("t:"+t);
String tt[] = t.split("\\s{1,}");//按照空格分割字符串,多个空格作为一个空格对字符串进行分割
System.out.println(tt[tt.length-1]);
}
}
}
Pattern p=Pattern.compile(" ?(.+?) as (.+?) *?(,|from){1}?| *(.+?) *(,|from){1}?");
Matcher m=p.matcher(str);
while(m.find()){
if (m.group(2) != null)System.out.println(m.group(2));
if (m.group(4) != null)System.out.println(m.group(4));
改了下,现在应该没什么问题了
试试吧
Pattern p=Pattern.compile(" ?(.+?) as (.+?) *?(,|from){1}?| *(.+?) *(,|from){1}?");
Matcher m=p.matcher(str);
while(m.find()){
if (m.group(2) != null)System.out.println(m.group(2));
if (m.group(4) != null)System.out.println(m.group(4));
}只输出:
姓名
年龄
d