Reputation: 1323
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
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
Reputation: 113
Remove the space after the ',' for your desired output with single underscore.
String string = "Sathesh,Soundar"; //prints Sathesh_Soundar
Upvotes: -1