Sunday, August 26, 2012

replace continuous and repeated pat into single replacement


replace continuous and repeated pattern into a single replacement


 //"Reeeep chineese";  trap if pat == rep
    public static String replaceConsecutiveRepeatedPattern(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 = "&nbsp";
       rep = " ";
replaceConsecutiveRepeatedPattern will change str into
       "Aug 3 23:02:54 2012"