尝试通过 },{ 拆分时出现 PatternSyntaxException [英] PatternSyntaxException while trying to split by },{

查看:21
本文介绍了尝试通过 },{ 拆分时出现 PatternSyntaxException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图分解我通过网站上的 API 获得的数组,Java 已将该数组检索为 String.

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?

推荐答案

出于某种原因,它真的不喜欢 },{.

For some reason, it really doesn't like },{.

这是因为大括号(}{)是 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.

转义这个字符串的正确方法是什么?

What is the proper way to escape this String?

也可以通过将它们加倍来逃避反斜杠.这是用于 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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