?? 今天在工作中,遇到這樣的情況。首先給你一個SQL語句,比如:
??? select * from tableA union select * from tableB
????要根據關鍵字把兩個查詢語句分解出來,即得到
?? select * from tableA 和 select * from tableB
?? 一般的做法是:
?String sql="select * from tableA union select * from tableB";
?? if(sql.toLowerCase().indexOf(" union ")>-1){
??? String sql2[]=sql.split(" union ");
??? for(int i=0;i<sql2.length;i++){
????? System.out.println(sql2[i]);
??? }
? }
?但因為這個是SQL語句,union關鍵字不區分大小寫的,所有sql語句有這些情況:
?select * from tableA?UNION select * from tableB
?select * from tableA?UnIOn select * from tableB
?select * from tableA?UNiON select * from tableB
?……
所以單單用這樣的語句:String sql2[]=sql.split(" union ");
是分解不出子語句的。
這里的碰到了特殊情況,我不知道別人是怎么做的,我的思路是應該有種機制sql.split(不區分大小寫);
String類沒提供該方法,于是我覺得先看看SUN的源碼,了解它的源碼
是怎么處理的,找到了:
public int indexOf(String str) {
?return indexOf(str, 0);
??? }
?public String[] split(String regex, int limit) {
?return Pattern.compile(regex).split(this, limit);
??? }
它運用的不過是正則表達式而已,幸好這幾天對正則表達式有所研究。
看看正則表達式:
DEELX 正則表達式匹配模式
IGNORECASE
匹配時忽略大小寫。默認情況下,正則表達式是要區分大小寫的。不管是否指定忽略大小寫模式,字符類,比如 [A-Z] 是要區分大小寫的。
DEELX 支持對
IGNORECASE, SINGLELINE, MULITLINE, GLOBAL 進行修改?
a(b(?i)c)d | 增加 i - IGNORECASE 模式,只對 c 起作用。表達式可以匹配 "abcd" 和 "abCd" |
所以我們把
String sql2[]=sql.split(" union ");
修改為
String sql2[]=sql.split(" (?i)union ");
問題即可迎刃而解。
完整的:
String sql="select * from tableA union select * from tableB";
?? if(sql.toLowerCase().indexOf(" union ")>-1){
??? String sql2[]=sql.split(" (?i)union ");
??? for(int i=0;i<sql2.length;i++){
????? System.out.println(sql2[i]);
??? }
? }
打印結果:
select * from tableA
select * from tableB
posted on 2008-05-04 10:13
蔣家狂潮 閱讀(2221)
評論(5) 編輯 收藏 所屬分類:
Basic