replace special characters in string in java

前端 未结 4 437
没有蜡笔的小新
没有蜡笔的小新 2020-12-02 02:22

I want to know how to replace the string in Java.

E.g.

String a = \"adf�sdf\";

How can I replace and avoid special characters?

相关标签:
4条回答
  • 2020-12-02 02:33

    Assuming, that you want to remove all special characters, you can use the character class \p{Cntrl} Then you only need to use the following code:

    stringWithSpecialCharcters.replaceAll("\\p{Cntrl}", replacement);
    
    0 讨论(0)
  • 2020-12-02 02:35

    You can get rid of all characters outside the printable ASCII range using String#replaceAll() by replacing the pattern [^\\x20-\\x7e] with an empty string:

    a = a.replaceAll("[^\\x20-\\x7e]", "");
    

    But this actually doesn't solve your actual problem. It's more a workaround. With the given information it's hard to nail down the root cause of this problem, but reading either of those articles must help a lot:

    • The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
    • Unicode - How to get the characters right?
    0 讨论(0)
  • 2020-12-02 02:40

    It is hard to answer the question without knowing more of the context.

    In general you might have an encoding problem. See The Absolute Minimum Every Software Developer (...) Must Know About Unicode and Character Sets for an overview about character encodings.

    0 讨论(0)
  • 2020-12-02 02:56

    You can use unicode escape sequences (such as \u201c [an opening curly quote]) to "avoid" characters that can't be directly used in your source file encoding (which defaults to the default encoding for your your platform, but you can change it with the -encoding parameter to javac).

    0 讨论(0)
提交回复
热议问题