user1436111
user1436111

Reputation: 2141

Java regex to match curly braces - "invalid escape sequence"

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

Answers (5)

Suzan Cioc
Suzan Cioc

Reputation: 30127

1. Curle braces have no special meaning here for regexp language, so they should not be escaped I think.

  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.

  2. There are good JSON parsing libraries 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"}

Upvotes: 19

11684
11684

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

Rohit Jain
Rohit Jain

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

Anirudha
Anirudha

Reputation: 32807

The regular expression should be

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

. is not required!

Upvotes: 4

Double the backslashes:

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

Upvotes: 3

Related Questions