简体   繁体   English

Java 正则表达式匹配花括号 - “无效的转义序列”

[英]Java regex to match curly braces - “invalid escape sequence”

I want to parse nested JSON strings by splitting them up recursively by { }.我想通过用 { } 递归拆分嵌套的 JSON 字符串来解析它们。 The regex I came up with is "{([^}]*.?)}", which I've tested appropriately grabs the string I want.我想出的正则表达式是“{([^}]*.?)}”,我已经适当地测试了它可以抓取我想要的字符串。 However, when I try to include it in my Java I get the following error: "Invalid escape sequence (valid ones are \\b \\t \\n \\f \\r \\" \\' \\ )"但是,当我尝试将它包含在我的 Java 中时,我收到以下错误:“无效的转义序列(有效的转义序列是 \\b \\t \\n \\f \\r \\” \\' \\ )”

This is my code, and where the error occurs:这是我的代码,以及发生错误的地方:

String[] strArr = jsonText.split("\{([^}]*.?)\}");

What am I doing wrong?我究竟做错了什么?

The nasty thing about Java regexes is that java doesn't recognize a regex as a regex. Java 正则表达式的糟糕之处在于,java 无法将正则表达式识别为正则表达式。
It accepts only \\\\ , \\' , \\" or \\u[hexadecimal number] as valid escape sequences. You'll thus have to escape the backslashes because obviously \\{ is an invalid escape sequence.它只接受\\\\\\'\\"\\u[hexadecimal number]作为有效的转义序列。因此您必须对反斜杠进行转义,因为显然\\{是一个无效的转义序列。
Corrected version:修正版:

String[] strArr = jsonText.split("\\{([^}]*.?)\\}");

1. Curle braces have no special meaning here for regexp language, so they should not be escaped I think. 1.花括号在这里对于正则表达式语言没有特殊意义,所以我认为它们不应该被转义。

  1. If you want to escape them, you can.如果你想逃避他们,你可以。 Backslash is an escape symbol for regexp, but it also should be escaped for Java itself with second backslash.反斜杠是正则表达式的转义符号,但对于 Java 本身,它也应该使用第二个反斜杠进行转义。

  2. There are good JSON parsing libraries https://stackoverflow.com/questions/338586/a-better-java-json-library有很好的 JSON 解析库https://stackoverflow.com/questions/338586/a-better-java-json-library

  3. You are using reluctant quantifier, so it won't work with nested braces, for example for {"a", {"b", "c"}, "d"} it will match {"a", {"b", "c"}您使用的是不情愿量词,因此它不适用于嵌套大括号,例如对于{"a", {"b", "c"}, "d"}它将匹配{"a", {"b", "c"}

You need to escape your backslash with one more backslash.你需要用一个反斜杠来逃避你的反斜杠。 Since, \\{ is not a valid escape sequence: -因为, \\{不是有效的转义序列:-

String[] strArr = jsonText.split("\\{([^\\}]*.?)\\}");

You can refer to Pattern documentation for more information about escape sequences.您可以参考Pattern 文档以获取有关转义序列的更多信息。

The regular expression should be正则表达式应该是

"\\{([^}]*?)\\}"

. is not required!不需要!

双反斜杠:

String[] strArr = jsonText.split("\\{([^}]*.?)\\}");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM