I have a string s and a regex. I would like to replace every regular expression match in s with a replacement string. A replacement string may contain one or more backslashes. To do the replacement, I use the Matcher method appendReplacement .
The problem with appendReplacement is that it ignores all the gaps it encounters in the replacement string. Therefore, if I try to replace the substring "match" in the string "one match" with the replacement string "a\\b" , then appendReplacement will result in "one ab" instead of "one a\\b" *:
Matcher matcher = Pattern.compile("match").matcher("one match"); StringBuffer sb = new StringBuffer(); matcher.find(); matcher.appendReplacement(sb, "a\\b"); System.out.println(sb);
I looked at the appendReplacement code and found out that it skips any counter backslash:
if (nextChar == '\\') { cursor++ nextChar = replacement.charAt(cursor); ... }
How to replace each match with a replacement string containing a backslash?
(*) - Note that in "a\\b" there is one backslash, not two. The backslash just escaped.
source share