用于匹配花括号的Java正则表达式 - “无效的转义序列” [英] Java regex to match curly braces - "invalid escape sequence"

查看:459
本文介绍了用于匹配花括号的Java正则表达式 - “无效的转义序列”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望通过{}递归地将它们拆分来解析嵌套的JSON字符串。我提出的正则表达式是{([^}] *。?)},我已经测试适当地抓住我想要的字符串。但是,当我尝试将其包含在我的Java中时,我收到以下错误:无效的转义序列(有效转义序列为\b \t \ n \f \ r \\'\)

I want to parse nested JSON strings by splitting them up recursively by { }. 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 \" \' \ )"

这是我的代码,以及发生错误的地方:

This is my code, and where the error occurs:

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

我做错了什么?

推荐答案

1.这里没有特殊含义的花括号对于正则表达式语言,我认为它们不应该被转义。


  1. 如果你想要为了逃避它们,你可以。反斜杠是regexp的转义符号,但它也应该用Java本身进行第二次反斜杠转义。

  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.

为什么不你在分组构造中逃脱了curle大括号吗?

Why don't you escape curle brace inside grouping construct?

有很好的JSON解析库 https://stackoverflow.com/q uestions / 338586 / a-better-java-json-library

There are good JSON parsing libraries https://stackoverflow.com/questions/338586/a-better-java-json-library

您正在使用不情愿的量词,因此它不适用于嵌套括号,例如 {a,{b,c},d} 它将匹配 {a, {b,c}

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"}

这篇关于用于匹配花括号的Java正则表达式 - “无效的转义序列”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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