Full: Matcher m = Pattern.compile("(#\\d+)").matcher(text); new StringBuffer buf; // cool "quicknew" syntax! while (m.find()) m.appendReplacement(buf, m.quoteReplacement(formatSnippetRef(m.group()))); m.appendTail(buf); text = buf.toString(); Short: text = text.replaceAll("(#\\d+)", m -> formatSnippetRef(m.group()));