user2816352
user2816352

Reputation: 335

Invalid Java Regex for JSON

For some reason this regex keeps saying it is invalid in java, but on the online testers it works fine:

({.+?})

I am using it for a JSON data structure.

Is there a way to get it to work with Java?

Included link: http://regexr.com/3bs0p

Upvotes: 2

Views: 316

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

Here are my 2 cents:

  1. You need to escape the opening { in Java regex to tell the engine it is not the brace starting the limiting quantifier.
  2. Do not use regexr.com to test Java regexps, use OCPSoft Visual Regex Tester or RegexPlanet that support Java regex syntax.
  3. Do not use round brackets around the whole pattern, you can always refer to it with .group(0) or $0 back-reference.

The regex should look like

String pattern = "\\{.+?}"; // Note that `.+?` requires at least 1 character,
                            // Use .*? to allow 0 characters

And

  1. Do not parse JSON with regex. See How to parse JSON in Java.

Upvotes: 1

Trevor Freeman
Trevor Freeman

Reputation: 7232

You probably need to escape your { } with backslashes, since you are treating them as literal characters.

E.g.

(\\{.+?\\})

Upvotes: 1

Related Questions