Remove non-ASCII non-printable characters from a String

后端 未结 6 2269
轻奢々
轻奢々 2020-12-02 13:56

I get user input including non-ASCII characters and non-printable characters, such as

\\xc2d
\\xa0
\\xe7
\\xc3\\ufffdd
\\xc3\\ufffdd
\\xc2\\xa0
\\xc3\\xa7
         


        
相关标签:
6条回答
  • 2020-12-02 14:13

    Your requirements are not clear. All characters in a Java String are Unicode characters, so if you remove them, you'll be left with an empty string. I assume what you mean is that you want to remove any non-ASCII, non-printable characters.

    String clean = str.replaceAll("\\P{Print}", "");
    

    Here, \p{Print} represents a POSIX character class for printable ASCII characters, while \P{Print} is the complement of that class. With this expression, all characters that are not printable ASCII are replaced with the empty string. (The extra backslash is because \ starts an escape sequence in string literals.)


    Apparently, all the input characters are actually ASCII characters that represent a printable encoding of non-printable or non-ASCII characters. Mongo shouldn't have any trouble with these strings, because they contain only plain printable ASCII characters.

    This all sounds a little fishy to me. What I believe is happening is that the data really do contain non-printable and non-ASCII characters, and another component (like a logging framework) is replacing these with a printable representation. In your simple tests, you are failing to translate the printable representation back to the original string, so you mistakenly believe the first regular expression is not working.

    That's my guess, but if I've misread the situation and you really do need to strip out literal \xHH escapes, you can do it with the following regular expression.

    String clean = str.replaceAll("\\\\x\\p{XDigit}{2}", "");
    

    The API documentation for the Pattern class does a good job of listing all of the syntax supported by Java's regex library. For more elaboration on what all of the syntax means, I have found the Regular-Expressions.info site very helpful.

    0 讨论(0)
  • 2020-12-02 14:19

    You can try this code:

    public String cleanInvalidCharacters(String in) {
        StringBuilder out = new StringBuilder();
        char current;
        if (in == null || ("".equals(in))) {
            return "";
        }
        for (int i = 0; i < in.length(); i++) {
            current = in.charAt(i);
            if ((current == 0x9)
                    || (current == 0xA)
                    || (current == 0xD)
                    || ((current >= 0x20) && (current <= 0xD7FF))
                    || ((current >= 0xE000) && (current <= 0xFFFD))
                    || ((current >= 0x10000) && (current <= 0x10FFFF))) {
                out.append(current);
            }
    
        }
        return out.toString().replaceAll("\\s", " ");
    }
    

    It works for me to remove invalid characters from String.

    0 讨论(0)
  • 2020-12-02 14:20

    With Google Guava's CharMatcher, you can remove any non-printable characters and then retain all ASCII characters (dropping any accents) like this:

    String printable = CharMatcher.INVISIBLE.removeFrom(input);
    String clean = CharMatcher.ASCII.retainFrom(printable);
    

    Not sure if that's what you really want, but it removes anything expressed as escape sequences in your question's sample data.

    0 讨论(0)
  • 2020-12-02 14:24

    I know it's maybe late but for future reference:

    String clean = str.replaceAll("\\P{Print}", "");
    

    Removes all non printable characters, but that includes \n (line feed), \t(tab) and \r(carriage return), and sometimes you want to keep those characters.

    For that problem use inverted logic:

    String clean = str.replaceAll("[^\\n\\r\\t\\p{Print}]", "");
    
    0 讨论(0)
  • 2020-12-02 14:24

    You can use java.text.normalizer

    0 讨论(0)
  • 2020-12-02 14:37

    Input => "This \u7279text \u7279is what I need" Output => "This text is what I need"

    If you are trying to remove Unicode characters from a string like above this code will work

    Pattern unicodeCharsPattern = Pattern.compile("\\\\u(\\p{XDigit}{4})");
    Matcher unicodeMatcher = unicodeChars.matcher(data);
    String cleanData = null;
    if (unicodeMatcher.find()) {
        cleanData = unicodeMatcher.replaceAll("");
    }
    
    0 讨论(0)
提交回复
热议问题