How do I remove some characters from my String

You can use the replaceAll method of the String class.

You can form a character class consisting of the characters you want to delete. And the replacement string will be empty string "".

But the characters you want to delete which you'll be putting in the character class might be regex meta-characters and hence need to be escaped. You can manually escape them as many answers show, alternatively you can use the Pattern.quote() method.

String charToDel = ">[],-";
String pat = "[" + Pattern.quote(charToDel) + "]";
String str = "a>b[c]d,e-f";
str = str.replaceAll(pat,"");

See it


Use a regex that describes all the characters you want to replace, with the method that replaces everything matching the regex:

newString = myString.replaceAll("[<>\\[\\],-]", "");

(edited: I don't think <> are supposed to be escaped, actually. And I forgot to double up the backslashes since they'll be interpreted twice: once by the Java compiler, and again by the regular expression engine.)

Tags:

Java

String