Question

I am using Jre 1.6. I am executing the following lines of code:

String unicodeValue = "\u001B"; text = text.replaceAll("" + character, unicodeValue);

Here, text is a string object containing an invalid XML character of Unicode value '\u001B'. So, I am converting the invalid XML character to its Unicode value to write in the XML.

But on doing text.replaceAll, the '\' is getting stripped and the character is replaced by 'u001B'.

Can anyone please suggest a way to retain the '\' after replacing the character with its unicode value ?

Was it helpful?

Solution

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.

OTHER TIPS

Use double slash \\ to represent escaped \:

String unicodeValue = "\\u001B"; text = text.replaceAll("" + character, unicodeValue);

This ran perfect. I tested it.

    char character = 0x1b;
    String unicodeValue = "\\\\u001B"; 
    String text = "invalid " + character + " string";
    System.out.println(text);
    text = text.replaceAll("" + character, unicodeValue);
    System.out.println(text);

Just used a concept of RegEx.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top