Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing an invalid escape sequence from a Java String

Tags:

java

I have an invalid escape sequence inside a json string. The sequence is:

'ngram': "'s\xa0cancer prevention"

I have been trying to remove this sequence completely by replacing it with a blank string, however each attempt fails. I have tried the following ways:

qumlsOutputAsJson = qumlsOutputAsJson.replaceAll("[^\\x20-\\x7E]", "");

and

qumlsOutputAsJson = qumlsOutputAsJson.replaceAll("\\.", "");

and even a routine:

    private String removeNonAscii(String text){
    String asciiText = "";
    for (char aChar: text.toCharArray()){
        if((int)aChar<=0x7F)
            asciiText = asciiText + Character.toString(aChar);
    }
    return asciiText;
}

All have failed.

I'm sure there is an obvious way, but any direction much appreciated.

like image 608
WaterBoy Avatar asked Aug 06 '26 15:08

WaterBoy


1 Answers

With replaceAll you need to escape the backslash, i.e. "\\\\",""

If you just used replace, yours should work as expected

qumlsOutputAsJson = qumlsOutputAsJson.replaceAll("\\\\", "");
like image 138
achAmháin Avatar answered Aug 08 '26 03:08

achAmháin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!