Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to remove square brackets from a string, but I don't know how.

String str = "[Chrissman-@1]";
str = replaceAll("\[\]", "");

String[] temp = str.split("-@");
System.out.println("Nickname: " + temp[0] + " | Power: " + temp[1]);

But my result is: [Chrissman | 1] The square brackets doesn't get removed.

I tried using a different regex: "\[.*?\]", "\[\d+\]" but the result is the same, the square brackets still attached on the string.

Edit:

I tried:

str.replaceAll("]", "");
str.replaceAll("[", "");

And now I'm getting:

Exception in thread "Thread-4" java.util.regex.PatternSyntaxException: Unclosed character class near index 0
[
^
    at java.util.regex.Pattern.error(Unknown Source)
    at java.util.regex.Pattern.clazz(Unknown Source)
    at java.util.regex.Pattern.sequence(Unknown Source)
    at java.util.regex.Pattern.expr(Unknown Source)
    at java.util.regex.Pattern.compile(Unknown Source)
    at java.util.regex.Pattern.<init>(Unknown Source)
    at java.util.regex.Pattern.compile(Unknown Source)
    at java.lang.String.replaceAll(Unknown Source)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
876 views
Welcome To Ask or Share your Answers For Others

1 Answer

The replaceAll method is attempting to match the String literal [] which does not exist within the String try replacing these items separately.

String str = "[Chrissman-@1]";
str = str.replaceAll("\[", "").replaceAll("\]","");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...