简体   繁体   中英

replace special characters in string in java

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

Eg

String a = "adf�sdf";

How can I replace and avoid special characters?

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:

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.

假设您要删除所有特殊字符,可以使用字符类\\p{Cntrl}然后您只需要使用以下代码:

stringWithSpecialCharcters.replaceAll("\\p{Cntrl}", replacement);

您可以使用unicode转义序列(例如\“ [开头的卷曲引号])来“避免”无法直接用于源文件编码的字符(默认为您的平台的默认编码,但您可以使用-encoding参数将其更改为javac )。

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