replace continuous and repeated pattern into a single replacement
//"Reeeep chineese"; trap if pat == rep
public static String replaceConsecutiveRepea tedPattern(String str, String pat, String rep) {
if (pat == null || pat.length() == 0) return str;
int id = str.indexOf(pat);
StringBuilder sb = new StringBuilder();
while (id >= 0) {
sb.append(str.substring(0, id));
str = str.substring(id);
while (str.startsWith(pat, pat.length())) {
str = str.replaceFirst(pat, "");
}
str = str.replaceFirst(pat, rep);
id = str.indexOf(pat, rep.length());
}
sb.append(str);
return sb.toString();
}
for example:
with
str = "Aug 3 23:02:54 2012";
pat = " ";
rep = " ";
replaceConsecutiveRepeatedPattern will change str into
"Aug 3 23:02:54 2012"