Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for special characters in java

public static final String specialChars1= "\\W\\S";
String str2 = str1.replaceAll(specialChars1, "").replace(" ", "+");

public static final String specialChars2 = "`~!@#$%^&*()_+[]\\;\',./{}|:\"<>?";
String str2 = str1.replaceAll(specialChars2, "").replace(" ", "+");

Whatever str1 is I want all the characters other than letters and numbers to be removed, and spaces to be replaced by a plus sign (+).

My problem is if I use specialChar1, it does not remove some characters like ;, ', ", and if I am use specialChar2 it gives me an error :

java.util.regex.PatternSyntaxException: Syntax error U_REGEX_MISSING_CLOSE_BRACKET near index 32:

How can this be to achieved?. I have searched but could not find a perfect solution.

like image 513
Housefly Avatar asked Nov 29 '22 09:11

Housefly


2 Answers

This worked for me:

String result = str.replaceAll("[^\\dA-Za-z ]", "").replaceAll("\\s+", "+");

For this input string:

/-+!@#$%^&())";:[]{}\ |wetyk 678dfgh

It yielded this result:

+wetyk+678dfgh

like image 192
npinti Avatar answered Dec 04 '22 01:12

npinti


replaceAll expects a regex:

public static final String specialChars2 = "[`~!@#$%^&*()_+[\\]\\\\;\',./{}|:\"<>?]";
like image 29
Joey Avatar answered Dec 04 '22 02:12

Joey