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

3

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?

Precentor answered 3/9, 2013 at 18:21 Comment(1)
May not be the perfect duplicate example, but this question has been asked dozens of times.Irritated
S
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_]
Submarginal answered 3/9, 2013 at 18:22 Comment(0)
A
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]", "");
Aphelion answered 3/9, 2013 at 18:42 Comment(0)
F
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.

Forty answered 3/9, 2013 at 18:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.