Java can't replace “{” with replaceAll method
本问题已经有最佳答案,请猛点这里访问。
我们正在使用String的replaceAll方法,并且不能在任何字符串中替换{。
我们的例子:
尝试过:
1 | "some { string".replaceAll("{","other string"); |
错误如下:
java.util.regex.PatternSyntaxException: Illegal repetition occurs
开放任何想法! 也许有解决方法?!
使用replaceAll需要一个正则表达式(regex)
尝试使用replace方法而不是replaceAll
1 | "some { string".replace("{","other string"); |
或使用
1 | "some { string".replaceAll("\\\\{","other string"); |
像这样尝试
1 | "some { string".replace("{","other string"); |
或将
1 | "some { string".replaceAll("\\\\{","your string to replace"); |
注意:对于
您需要转义
1 |
{是正则表达式引擎的指示符,您即将开始一个重复指示符,例如{2,4},表示"是先前标记的2到4倍"。
但是{f是非法的,因为必须在其后跟数字,所以它引发异常。
你可以做这样的事情
1 | "some { string".replaceAll("\\\\{","other string"); |
您需要转义字符" {"。
试试这个 :
1 | "some { string".replaceAll("\\\\{","other string"); |
您必须使用转义字符
1 | "some { string".replaceAll("\\\\{","other string"); |
字符
" xxx" .replace(" {"," xxx")
" xxx" .replace(" \ {"," xxx")
字符串replace()和replaceAll()之间的区别