The appendReplacement matching method ignores backslash replacements

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); // one ab 

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.

+5
source share
2 answers

You need to double the escape backslash ie:

 matcher.appendReplacement(sb, "a\\\\b"); 

Full code:

 Matcher matcher = Pattern.compile("match").matcher("one match"); sb = new StringBuffer(); matcher.find(); matcher.appendReplacement(sb, "a\\\\b"); System.out.println(sb); //-> one a/b 

The reason is because Java allows backlinks like $1 , $2 , etc. to be used. in the replacement string, and which provides the same escaping mechanism for the backslash as in the main regular expression.

+2
source

You need to avoid screens

 Matcher matcher = Pattern.compile("match").matcher("one match"); StringBuffer sb = new StringBuffer(); matcher.find(); matcher.appendReplacement(sb, "a\\\\b"); System.out.println(sb); 

Alternatively use replace ()

 String test="one match"; test=test.replace("match", "a\\b"); System.out.println(test); 

conclusion:

 one a\b 
+2
source

Source: https://habr.com/ru/post/1208659/


All Articles