Java替换字符串中的所有方括号 [英] Java replace all square brackets in a string

查看:867
本文介绍了Java替换字符串中的所有方括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从字符串中删除方括号,但我不知道如何。

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]);

但我的结果是:[Chrissman | 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.

编辑:

我试过:

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

现在我收到:

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)


推荐答案

replaceAll方法正在尝试匹配字符串文字 [] 字符串中不存在尝试单独替换这些项目。

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("\\]","");

这篇关于Java替换字符串中的所有方括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆