I am trying to write java code which would remove all unwanted characters and let there be only whitelisted ones.
Example:
String[] whitelist = {"a", "b", "c"..."z", "0"..."9", "[", "]",...}
I want there only letters (lower and uppercase) and numbers + some next characters I would add.
Then I would start for()
cycle for every character in the string, and replace it with empty string if it isn't on whitelist.
But that isn't good solution. Maybe it could be done somehow using pattern (regex)? Thanks.
Yes, you can use
String.replaceAll
which takes a regex:Or in Guava you could use a
CharMatcher
:That just shows the lower case version, making it easier to demonstrate. To include upper case letters, use
"[^A-Za-z0-9\\[\\]]"
in the regex (and any other symbols you want) - and for theCharMatcher
you canor
it withCharMatcher.inRange('A', 'Z')
.You could try and match everything that is not in your whitelist and replace it with an empty string: