2

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?

1
  • You probably need to escape all the special characters, not just `` Commented Feb 6, 2011 at 18:30

3 Answers 3

4

Some of the characters are special characters that are being interpreted differently. You can either escape them all with backslashes, or better yet put them in a character class (no need to escape the non-CC characters, eases readability):

Pattern cleanPattern = Pattern.compile("[%\\\\,\\[\\]#&@!^]");
Sign up to request clarification or add additional context in comments.

1 Comment

you'll have to escape the literal [ and ] in the char class.
3

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 characters a, 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 [%\\\\,\\[\\]#&@!\\^].

2 Comments

It is incredible that people put up with evil monstrosities like [%\\\\,\\\[\\\]#&@!\\^]. Truly incredible! There has got to be a better way!!
I was thinking the same about the ^ but it seems it only has special meaning at the beginning of the character class, and doesn't need escaping at the end.
0

You'd define your pattern as a character group enclosed in [ and ] and escape special chars, e.g.

String n = "%\\,[]#&@!^".replaceAll("[%\\\\,\\[\\]#&@!^]", "");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.