Pattern pattern = Pattern.compile("\\?");
String text = "select a,b,c from table1 where a = ? and x = ? ";
int index = 1;
StringBuffer buffer = new StringBuffer();
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
matcher.appendReplacement(buffer, "?" + (index++));
}
matcher.appendTail(buffer);
System.out.println(buffer.toString());
// select a,b,c from table1 where a = ?1 and x = ?2
String s1 = "select a,b,c from table1 where a = ? and x = ? ";
String s2= s1.replaceFirst("[?]","1");
String s3= s2.replace('?','2');
System.out.println(s3);//s3 是最后结果
此方法设计用于循环以及 appendTail 和 find 方法中。例如,以下代码将 one dog two dogs in the yard 写入标准输出流中:
Pattern p = Pattern.compile("cat");
Matcher m = p.matcher("one cat two cats in the yard");
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, "dog");
}
m.appendTail(sb);
System.out.println(sb.toString());
正则