问题描述
我正在尝试拆分我在网站上通过API获取的数组,Java已将其检索为字符串
。
I am trying to break up an array I got through an API on a site, which Java has retrieved as a String
.
String[] ex = exampleString.split("},{");
抛出 PatternSyntaxException
。出于某种原因,它确实不喜欢},{
。
我已经尝试将其转义为 \ {
,但它表示这是非法逃脱。
A PatternSyntaxException
is thrown. For some reason, it really doesn't like },{
.I have tried escaping it as \{
, but it says it is an illegal escape.
逃避这个字符串的正确方法是什么?
What is the proper way to escape this string?
推荐答案
这是因为大括号(}
和 {
)是Java正则表达式中的特殊字符。如果你试图在没有转义的情况下逐字地使用它们,那么它被认为是语法错误,因此你的例外。
This is because braces (}
and {
) are special characters in Java regular expressions. If you try to use them literally without escaping, it's considered a syntax error, hence your exception.
通过加倍来逃避反斜杠。这适用于Java字符串转义。转义后的反斜杠将转义正则表达式的大括号。
Escape the backslashes too, by doubling them. This is for Java string escapes. The escaped backslashes will then escape the braces for the regex.
String[] ex = exampleString.split("\\},\\{");
这篇关于尝试按},{分割时出现PatternSyntaxException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!