I use the code to remove all the special chars from a string, but its removing the white spaces also. how can I exclude spaces ?ie I need to have the white spaces as it is.
String alphaAndDigits = keyword.replaceAll("[^a-zA-Z0-9]+","");
String alphaAndDigits = keyword.replaceAll("[^A-Za-z\\d\\s]+","");
\\s
is the matcher for whitespaces [ \\t\\n\\x0b\\r\\f]
\\d
is the matcher for digits [0-9]
String alphaAndDigits = keyword.replaceAll("[^A-Za-z0-9 \\t\\n\\x0b\\r\\f]+","");
would be the same if you prefer that
String alphaAndDigits = "hello&%*..sad**";
Pattern ptn = Pattern.compile("[^S a-zA-Z0-9]");
Matcher match = ptn.matcher(alphaAndDigits);
while (match.find()) {
String str = match.group();
alphaAndDigits =alphaAndDigits.replaceAll("\\" + str, "");
}
System.out.println(alphaAndDigits);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.