我有这样一句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());
输出结果:
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()方法。