Sathesh S
Sathesh S

Reputation: 1323

Replace multiple occurrences of a Special character with a Single character

I want to replace Special character with Underscore. Issue I'm facing is instead of replacing with single underscore there are 2 underscores appearing. Below is my code.

String string = "Sathesh, Soundar";
System.out.println(string.replaceAll("[,\\s]","_"));

Here i'm getting the output as Sathesh__Soundar. Instead of this i want to get Sathesh_Soundar. If I have some more continues special characters everything should be replaced with single underscore.

Upvotes: 0

Views: 1955

Answers (3)

Shafin Mahmud
Shafin Mahmud

Reputation: 4071

First of all you need to define what is special character. I assume you define this as - all characters except alpha numeric. Then the regex should be [^a-zA-Z0-9]+

This regex is explained as here.

And then the code should be as below

String string = "Sathesh, Soundar";
System.out.println(string.replaceAll("[^a-zA-Z0-9]+","_"));

Upvotes: 4

Srikanth.K
Srikanth.K

Reputation: 113

Remove the space after the ',' for your desired output with single underscore.

 String string = "Sathesh,Soundar"; //prints Sathesh_Soundar

Upvotes: -1

Avinash L
Avinash L

Reputation: 187

try using this

s.replaceAll("[^\\w\\d]+", "_");

Upvotes: 1

Related Questions