模式nsyntaxexception在嘗試分割},{ - PatternSyntaxException while trying to split by },{ -开发者知识库

模式nsyntaxexception在嘗試分割},{ - PatternSyntaxException while trying to split by },{ -开发者知识库,第1张

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[] 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.

PatternSyntaxException拋出。由於某些原因,它確實不喜歡},{。我曾試着逃離它,但它說這是非法逃逸。

What is the proper way to escape this string?

逃離這個字符串的正確方法是什么?

1 个解决方案

#1


15  

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字符串轉義的。然后,逃離的反斜杠將逃離regex的括號。

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

最佳答案:

本文经用户投稿或网站收集转载,如有侵权请联系本站。

发表评论

0条回复