一种是全量匹配,被替换的字符在该字符中只会存在一次
public class StringReplaseUtil extends org.springframework.util.StringUtils{
public static void main(String[] agrs){
String s = "AAASELECT AAA,AAA_B,AA_C,AA FROM DUAL AA_ AAA_";
System.out.println(replace(s,"AAA","a"));
}
public static String replace(String inString, String oldPattern, String newPattern) {
if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) {
return inString;
}
int index = inString.indexOf(oldPattern);
if (index == -1) {
// no occurrence -> can return input as-is
return inString;
}
int capacity = inString.length();
if (newPattern.length() > oldPattern.length()) {
capacity += 16;
}
StringBuilder sb = new StringBuilder(capacity);
int pos = 0;
int patLen = oldPattern.length();
while (index >= 0) {
String jz = inString.substring(index+patLen, index+patLen+1);
if(",".equals(jz) || " ".equals(jz)){
sb.append(inString.substring(pos, index));
sb.append(newPattern);
}else{
if(index > pos ){
sb.append(inString.substring(pos,index));
}else{
sb.append(inString.substring(pos,index+patLen));
}
}
pos = index + patLen;
index = inString.indexOf(oldPattern, pos);
if(index == -1){
sb.append(inString.substring(pos-patLen));
}
}
return sb.toString();
}
}
另外一种是被替换的字符在该字符串中会出现多次
public class StringReplaseUtil extends org.springframework.util.StringUtils{ public static void main(String[] agrs){ String s = "AAASELECT AAA,AAA_B,AA_C,AA,AAA AAAFROM DUAL AA_ AAA_"; System.out.println(replace(s,"AAA","a")); } public static String replace(String inString, String oldPattern, String newPattern) { if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) { return inString; } int index = inString.indexOf(oldPattern); if (index == -1) { // no occurrence -> can return input as-is return inString; } int capacity = inString.length(); if (newPattern.length() > oldPattern.length()) { capacity += 16; } StringBuilder sb = new StringBuilder(capacity); int pos = 0; int patLen = oldPattern.length(); while (index >= 0) { String jz = inString.substring(index+patLen, index+patLen+1); if(",".equals(jz) || " ".equals(jz)){ sb.append(inString.substring(pos, index)); sb.append(newPattern); }else{ sb.append(inString.substring(pos,index+patLen)); } pos = index + patLen; index = inString.indexOf(oldPattern, pos); if(index == -1){ sb.append(inString.substring(pos)); } } return sb.toString(); } }