2

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

user2816352
  • 335
  • 1
  • 5
  • 16
  • 3
    Why are you parsing JSON with regex? – Dave Newton Sep 24 '15 at 20:58
  • using a tool that requires it, i know its not the best idea but i'm doing small POC. – user2816352 Sep 24 '15 at 20:59
  • What error you are getting when you try to use this regex? Also do you know that `{` and `}` are special characters which can be used like `[a-z]{n}` to find `n` characters in range `a-z`? – Pshemo Sep 24 '15 at 21:01
  • "Not a Valid Java Regular Expression". When I use it on this online tool i get errors as well: http://java-regex-tester.appspot.com – user2816352 Sep 24 '15 at 21:03
  • Put that error message into your question and provide simple code example which will let us reproduce it. BTW you can test if your string represent valid regex by using `Pattern.compile(regex)`. If there are any problems with your regex you should be informed about them. – Pshemo Sep 24 '15 at 21:04

2 Answers2

1

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

E.g.

(\\{.+?\\})
Trevor Freeman
  • 7,112
  • 2
  • 21
  • 40
1

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.
Community
  • 1
  • 1
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563