public static final String specialChars1= \"\\\\W\\\\S\";
String str2 = str1.replaceAll(specialChars1, \"\").replace(\" \", \"+\");
public static final String speci
The problem with your first regex, is that "\W\S"
means find a sequence of two characters, the first of which is not a letter or a number followed by a character which is not whitespace.
What you mean is "[^\w\s]"
. Which means: find a single character which is neither a letter nor a number nor whitespace. (we can't use "[\W\S]"
as this means find a character which is not a letter or a number OR is not whitespace -- which is essentially all printable character).
The second regex is a problem because you are trying to use reserved characters without escaping them. You can enclose them in []
where most characters (not all) do not have special meanings, but the whole thing would look very messy and you have to check that you haven't missed out any punctuation.
Example:
String sequence = "qwe 123 :@~ ";
String withoutSpecialChars = sequence.replaceAll("[^\\w\\s]", "");
String spacesAsPluses = withoutSpecialChars.replaceAll("\\s", "+");
System.out.println("without special chars: '"+withoutSpecialChars+ '\'');
System.out.println("spaces as pluses: '"+spacesAsPluses+'\'');
This outputs:
without special chars: 'qwe 123 '
spaces as pluses: 'qwe+123++'
If you want to group multiple spaces into one +
then use "\s+"
as your regex instead (remember to escape the slash).