I want to replace any one of these chars:
% \ , [ ] # & @ ! ^
… with empty string (“”).
I used this code:
String line = "[ybi-173]";
Pattern cleanPattern = Pattern.compile("%|\\|,|[|]|#|&|@|!|^");
Matcher matcher = cleanPattern.matcher(line);
line = matcher.replaceAll("");
But it doesn’t work.
What do I miss in this regular expression?
There are several reasons why your solution doesn’t work.
Several of the characters you wish to match have special meanings in regular expressions, including
^,[, and]. These must be escaped with a\character, but, to make matters worse, the\itself must be escaped so that the Java compiler will pass the\through to the regular expression constructor. So, to sum up step one, if you wish to match a]character, the Java string must look like"\\]".But, furthermore, this is a case for character classes
[], rather than the alternation operator|. If you want to match “any of the charactersa,b,c, that looks like[abc]. You character class would be[%\,[]#&@!^], but, because of the Java string escaping rules and the special meaning of certain characters, your regex will be[%\\\\,\\[\\]#&@!\\^].