我有這樣一句sql語句:select ${ 0},${ 1},${2 },${2 } from t where ${0}='${2}'。
我的目的是先找出所有的變量,并把變量的值替換為: V變量名。
String statement = "select ${ 0},${ 1},${2 },${2 } from t where ${0}='${2}'";
System.out.println(statement);
Matcher m = Pattern.compile("(\\$\\{\\s*(\\d+)\\s*\\})").matcher(statement);
StringBuffer buffer = new StringBuffer();
while(m.find()) {
System.out.println("Matched:'" + m.group(1) + "' at position " + m.start());
System.out.println("Matched:'" + m.group(2) + "' at position " + m.start());
int temp = Integer.parseInt(m.group(2));
if(temp == 0)
m.appendReplacement(buffer, "V0");
else if(temp == 1)
m.appendReplacement(buffer, "V1");
else if(temp == 2)
m.appendReplacement(buffer, "V2");
}
m.appendTail(buffer);
System.out.println(buffer.toString());
輸出結(jié)果:
select ${ 0},${ 1},${2 },${2 } from t where ${0}='${2}'
Matched:'${ 0}' at position 7
Matched:'0' at position 7
Matched:'${ 1}' at position 13
Matched:'1' at position 13
Matched:'${2 }' at position 19
Matched:'2' at position 19
Matched:'${2 }' at position 25
Matched:'2' at position 25
Matched:'${0}' at position 44
Matched:'0' at position 44
Matched:'${2}' at position 50
Matched:'2' at position 50
select V0,V1,V2,V2 from t where V0='V2'
這里要逐個替換就要使用類Matcher的appendReplacement()和appendTail()方法。
我的目的是先找出所有的變量,并把變量的值替換為: V變量名。
String statement = "select ${ 0},${ 1},${2 },${2 } from t where ${0}='${2}'";
System.out.println(statement);
Matcher m = Pattern.compile("(\\$\\{\\s*(\\d+)\\s*\\})").matcher(statement);
StringBuffer buffer = new StringBuffer();
while(m.find()) {
System.out.println("Matched:'" + m.group(1) + "' at position " + m.start());
System.out.println("Matched:'" + m.group(2) + "' at position " + m.start());
int temp = Integer.parseInt(m.group(2));
if(temp == 0)
m.appendReplacement(buffer, "V0");
else if(temp == 1)
m.appendReplacement(buffer, "V1");
else if(temp == 2)
m.appendReplacement(buffer, "V2");
}
m.appendTail(buffer);
System.out.println(buffer.toString());
輸出結(jié)果:
select ${ 0},${ 1},${2 },${2 } from t where ${0}='${2}'
Matched:'${ 0}' at position 7
Matched:'0' at position 7
Matched:'${ 1}' at position 13
Matched:'1' at position 13
Matched:'${2 }' at position 19
Matched:'2' at position 19
Matched:'${2 }' at position 25
Matched:'2' at position 25
Matched:'${0}' at position 44
Matched:'0' at position 44
Matched:'${2}' at position 50
Matched:'2' at position 50
select V0,V1,V2,V2 from t where V0='V2'
這里要逐個替換就要使用類Matcher的appendReplacement()和appendTail()方法。