1

I have a string I want to match, which has content inside curly brackets I want to parse with regex in Java.

The string looks like:

#{apgarscore} >= 0 && #{apgarscore} < 4 && #{apgarcomment} == ''

I try to use #\{(.+)\}

The result is that it for some reason matches

apgarscore} >= 0 && #{apgarscore} < 4 && #{apgarcomment

rather than three separate values.

I tested it with here which yields the same result.

Can anyone please help me understand what I need to do differently?

ndnenkov
  • 35,425
  • 9
  • 72
  • 104
Simen Russnes
  • 2,002
  • 2
  • 26
  • 56
  • Forget about lazy matching, it is not the best solution. Use a negated character class `[^{}]`: `#\{([^{}]+)\}`. – Wiktor Stribiżew Jan 05 '16 at 13:47
  • If you need to understand the difference between greedy `.+` vs. lazy `.*`, read [What do lazy and greedy mean in the context of regular expressions?](http://stackoverflow.com/questions/2301285/what-do-lazy-and-greedy-mean-in-the-context-of-regular-expressions). – Wiktor Stribiżew Jan 05 '16 at 13:49

1 Answers1

2

The problem is that the .+ is greedy. This means that it would try to match as many characters as possible. To make it non-greedy, add a question mark after that.

#\{(.+?)\}

See it in action

ndnenkov
  • 35,425
  • 9
  • 72
  • 104