Reputation: 1
I have been trying to solve this problem for a while now, I am using .replaceAll to remove any character in a String that is not a letter or number. I tried using Pattern.quote(), but I was unable to make it work correctly. Then I tried using \Q and \E, but it still isn't working, even with my frustrated attempts at varying numbers of backslashes. This is my first time trying to escape in this manner so any help would really be appreciated.
Here is the line in question:
return input.toLowerCase().replaceAll("\\Q !"#$%&'()*+,-./:;<=>?@[]\^_`~{}|\\E","");
Upvotes: 0
Views: 62
Reputation: 521339
One simple fix here would be to just put all special characters inside a character class:
String input = "abc%#$123";
input = input.toLowerCase().replaceAll("[!\"#$%&'()*+,\\-./:;<=>?@\\[\\]\\\\^_`~{}|]","");
System.out.println(input);
abc123
The character class admits most of your special characters as unescaped literals. Exceptions are double quotes, backslash, and opening/closing square brackets, which however still do require escaping.
Note: It might be much easier to just remove anything which is not alphanumeric, e.g.
input = input.replaceAll("[^A-Za-z0-9]", "");
But perhaps there are characters which the above would exclude but you really want to keep.
Upvotes: 1
Reputation: 320
return input.toLowerCase().replaceAll("[^A-Za-z0-9()\[\]]", "");
Source: How to remove invalid characters from a string?
Upvotes: 0