6

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?

user2743857
  • 81
  • 1
  • 1
  • 6

3 Answers3

19

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_]
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
13

Contrary to what some may claim, \w is not the same as [a-zA-Z0-9_]. \w also includes all characters from all languages (Chinese, Arabic, etc) that are letters or numbers (and the underscore).

Considering that you probably consider non-Latin letters/numbers to be "special", this will remove all "non-normal" characters:

message = message.replaceAll("[^a-zA-Z0-9]", "");
Bohemian
  • 412,405
  • 93
  • 575
  • 722
1

\w is the same [A-Za-z0-9_] which will strip all spaces and such (but not _). Much safer to whitelist whats allowed instead of removing individual charecters.

Chris Lohfink
  • 16,150
  • 1
  • 29
  • 38