The problem is that str.replaceAll(regex, repl)
is defined as returning the same as
Pattern.compile(regex).matcher(str).replaceAll(repl)
But the documentation for replaceAll
says,
Note that backslashes () and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.
So this means we need to add several extra layers of escaping:
public class Foo {
public static void main(String[] args)
{
String unicodeValue = "\u001B";
String escapedUnicodevalue = "\\\\u001B";
String text = "invalid" + unicodeValue + "string";
text = text.replaceAll(unicodeValue, escapedUnicodevalue);
System.out.println(text);
}
}
prints invalid\u001Bstring
as desired.