简体   繁体   中英

Removing an invalid escape sequence from a Java String

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.

With replaceAll you need to escape the backslash, ie "\\\\\\\\",""

If you just used replace , yours should work as expected

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM