java 尝试通过 },{ 拆分时出现 PatternSyntaxException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5925913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:28:44  来源:igfitidea点击:

PatternSyntaxException while trying to split by },{

javaregexexceptionescapingsplit

提问by CMahaff

I am trying to break up an array I got through an API on a site, which Java has retrieved as a String.

我正在尝试分解我通过站点上的 API 获得的数组,Java 已将该数组作为String.

String[] ex = exampleString.split("},{");

A PatternSyntaxExceptionis thrown. For some reason, it really doesn't like },{. I have tried escaping it as \{, but it says it is an illegal escape.

APatternSyntaxException被抛出。出于某种原因,它真的不喜欢},{. 我试过将它转义为\{,但它说这是非法转义。

What is the proper way to escape this string?

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

回答by BoltClock

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

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

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 正则表达式中的特殊字符。如果您尝试直接使用它们而不转义,则会被视为语法错误,因此您的例外。

What is the proper way to escape this String?

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

Escape the backslashes too, by doubling them. This is for Java string escapes. The escaped backslashes will then escape the braces for the regex.

也可以通过将它们加倍来逃避反斜杠。这是用于 Java 字符串转义。转义的反斜杠然后将转义正则表达式的大括号。

String[] ex = exampleString.split("\},\{");