Reputation: 2141
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("\{([^}]*.?)\}");
What am I doing wrong?
Upvotes: 24
Views: 72560
Reputation: 30127
1. Curle braces have no special meaning here for regexp language, so they should not be escaped I think.
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.
There are good JSON parsing libraries https://stackoverflow.com/questions/338586/a-better-java-json-library
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"}
Upvotes: 19
Reputation: 7517
The nasty thing about Java regexes is that java doesn't recognize a regex as a regex.
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.
Corrected version:
String[] strArr = jsonText.split("\\{([^}]*.?)\\}");
Upvotes: 24
Reputation: 213311
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.
Upvotes: 4
Reputation: 32807
The regular expression should be
"\\{([^}]*?)\\}"
.
is not required!
Upvotes: 4
Reputation: 26763
Double the backslashes:
String[] strArr = jsonText.split("\\{([^}]*.?)\\}");
Upvotes: 3