Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace special characters in string in java

Tags:

java

string

regex

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?

like image 986
zahir Avatar asked Apr 09 '10 14:04

zahir


3 Answers

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?
like image 179
BalusC Avatar answered Oct 17 '22 10:10

BalusC


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.

like image 20
Daniel Rikowski Avatar answered Oct 17 '22 10:10

Daniel Rikowski


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);
like image 23
ablaeul Avatar answered Oct 17 '22 09:10

ablaeul