尝试按 },{ 分割时出现 PatternSyntaxException
我正在尝试分解通过网站上的 API 获得的数组,Java 已将其作为 String
检索。
String[] ex = exampleString.split("},{");
抛出PatternSyntaxException
。由于某种原因,它确实不喜欢 },{
。 我尝试将其转义为 \{
,但它说这是非法转义。
转义该字符串的正确方法是什么?
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("},{");
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是因为大括号(
}
和{
)是 Java 正则表达式中的特殊字符。如果您尝试按字面意思使用它们而不转义,则会被视为语法错误,因此会出现异常。通过将反斜杠加倍来转义它们。这是用于 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.Escape the backslashes too, by doubling them. This is for Java string escapes. The escaped backslashes will then escape the braces for the regex.