Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replaceAll special characters in a string? [duplicate]

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?

like image 314
user2743857 Avatar asked Sep 03 '13 18:09

user2743857


1 Answers

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_]
like image 52
Rohit Jain Avatar answered Sep 22 '22 20:09

Rohit Jain