Q:

Java String Fix Contractions

Given the following string:
"...Cant you, because I cant, I just CANT."

How would one go about adding an ' in all instances of cant, while still preserving capitalization?
"...Can't you, because I can't, I just CAN'T."

Here's what I have so far. It works, but it seems unnecessarily slow complex:
public static String fix(String line) {
    if (line == null || line.isEmpty()) {
        return line;
    }

    StringBuilder builder = new StringBuilder();
    String[] split = line.split(" ");

    for (String word : split) {
        if (word.replaceAll("\\p{P}", "").equalsIgnoreCase("cant")) { // remove punctuation
            while (word.matches("^\\p{P}.*$")) {  // starts with punctuation
                builder.append(word.charAt(0));
                word = word.substring(1);
            }
            builder.append(word.substring(0, 3)); // can
            builder.append("'");                  // '
            builder.append(word.substring(3));    // t
        } else {
            builder.append(word);
        }

        builder.append(" ");
    }

    return builder.toString().trim();
}

A:

Case insensitive regex replacement with capture groups on the entire line should be faster:
public static String fix(String line) {
    if (line == null) {
        return null;
    }
    return line.replaceAll("(?i)\\b(can)(t)\\b", "$1'$2");
}

