Use an appendReplacement loop.
Here is a general purpose way to do it:
private static String replace(String input, Map<String, String> mappings) {
StringBuffer buf = new StringBuffer();
Matcher m = Pattern.compile(toRegex(mappings.keySet())).matcher(input);
while (m.find())
m.appendReplacement(buf, Matcher.quoteReplacement(mappings.get(m.group())));
return m.appendTail(buf).toString();
}
private static String toRegex(Collection<String> keys) {
return keys.stream().map(Pattern::quote).collect(Collectors.joining("|"));
}
If you're not using Java 8+, the second method would be:
private static String toRegex(Collection<String> keys) {
StringBuilder regex = new StringBuilder();
for (String key : keys) {
if (regex.length() != 0)
regex.append("|");
regex.append(Pattern.quote(key));
}
return regex.toString();
}
Test code
Map<String, String> mappings = new HashMap<>();
mappings.put("ck","k");
mappings.put("dd","wr");
mappings.put("f", "m");
System.out.println(replace("odd flock", mappings)); // prints: owr mlok
See IDEONE for running version.