How to replaceAll special characters in a string?

user2743857 picture user2743857 · Sep 3, 2013 · Viewed 54.1k times · Source

So to remove all the spaces in my string. I did a method that is consists of

message = message.replaceAll("\\s", "");

I was wondering if there was a command to remove and special character, like a comma, or period and just have it be a string. Do i have to remove them one by one or is there a piece of code that I am missing?

Answer

Rohit Jain picture Rohit Jain · Sep 3, 2013

You can go the other way round. Replace everything that is not word characters, using negated character class:

message = message.replaceAll("[^\\w]", "");

or

message = message.replaceAll("\\W", "");

Both of them will replace the characters apart from [a-zA-Z0-9_]. If you want to replace the underscore too, then use:

[\\W_]