有這樣一個串
Read([SQLServer#10.5.219.21#mas_db],[select * from material where machine_seq='!dbo.repair.machine_seq' and b='@@dbo.test.cc' and c='!!dbo.test.dd' and d='@dbo.repair' and e='sd.bf' and f='@aa.bg' and g='#dbo.repair.machine_name' and h=@dbo.repair.owner],[en_US])
需要解析中間的select * from material where machine_seq='!dbo.repair.machine_seq' and b='@@dbo.test.cc' and c='!!dbo.test.dd' and d='@dbo.repair' and e='sd.bf' and f='@aa.bg' and g='#dbo.repair.machine_name' and h=@dbo.repair.owner
還需要滿足'@@','@','!'(前后包含單引號),的變量取出來
@schema.table.fieldName @dbo.repair.machine_seq要點:獲取界面上某個控件錄入的值;
#schema.table #dbo.reapir要點:獲取這個表的記錄行數(shù);
!schema.table.fieldName !dbo.repair.qty要點:統(tǒng)計dbo.repair表qty總和. 相當于Sum(qty)性質(zhì).
@@constName @@User_ID要點:獲取內(nèi)存變量值;
實現(xiàn)如下:
package com.lenovo.nabf.util;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class NabfUtilTest {
public static final Pattern PatternSql = Pattern.compile("\\'(([#!]{1}|[@]{1,2})[\\w\\.]+?)\\'"); // match '@dbo.repair.machine_seq'
public static final Pattern PatternReadString = Pattern.compile(".+?,\\[([\\w\\.\\s{*!@#=\'}]+?)\\],.+?"); //match Read([db],[sqlstring],[lang])得到sqlstring的值
public static void main(String args[]){
String readString="Read([SQLServer#10.5.219.21#mas_db],[select * from material where "
+ "machine_seq='!dbo.repair.machine_seq' and b='@@dbo.test.cc' "
+ "and c='!!dbo.test.dd' and d='@dbo.repair' and e='sd.bf' and f='@aa.bg' "
+ "and g='#dbo.repair.machine_name' and h=@dbo.repair.owner],[en_US])";
System.out.println(readString);
System.out.println(analysisReadStr(readString));
List list=NabfUtil.getRegexMatchedList(readString);
for(String s:list){
System.out.println(s);
}
String sqlString = NabfUtil.getStringByAnalysisReadString(readString);
System.out.println(sqlString);
}
public static ArrayList getRegexMatchedList(String readString){
String sqlString = analysisReadStr(readString);
ArrayList matchList=new ArrayList();
Matcher matcher = PatternSql.matcher(sqlString);
int lastEndIndex = 0;
while (matcher.find(lastEndIndex)) {
matchList.add(matcher.group(1));
lastEndIndex = matcher.end();
}
return matchList;
}
public static String getStringByAnalysisReadString(String readString){
String sqlString = analysisReadStr(readString);
Matcher matcher = PatternSql.matcher(sqlString);
StringBuilder sb = new StringBuilder();
int lastEndIndex = 0;
while (matcher.find(lastEndIndex)) {
sb.append(sqlString.substring(lastEndIndex, matcher.start()));
lastEndIndex = matcher.end();
}
sb.append(sqlString.substring(lastEndIndex));
return sb.toString();
}
private static String analysisReadStr(String readString){
Matcher matcher = PatternReadString.matcher(readString);
int lastEndIndex = 0;
String sqlString="";
while (matcher.find(lastEndIndex)) {
sqlString=matcher.group(1);
lastEndIndex = matcher.end();
}
return sqlString;
}
}