Vraj Solanki
Vraj Solanki

Reputation: 359

Replacing multiple occurences of special characters by a single special character

I want to remove multiple occurrences of special characters like " ", "-", "!", "_" from my java string by a single underscore "_". I tried

replaceAll("([\\s\\-\\!])\\1+","_")

and it seems to replace consecutive same type of special character by a underscore but doesn't work otherwise. for eg:

Hello!!!  World

becomes

Hello__World

(2 underscores.)But It should be Hello_World.

Also for cases like Hello - World it fails. I also tried working with regex and made a regular expression like

replaceAll("([^a-zA-Z0-9])\\1+","_")

but it still doesn't help. How can I achieve it?

Upvotes: 3

Views: 1702

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626853

Note that \1 is a backreference to the contents matched with the first capturing group. To actually match one or more any characters from the character class, just use a + quantifier:

[\\s!-]+

So, use

str = str.replaceAll("[\\s!-]+","_");

See IDEONE demo

Upvotes: 4

Related Questions