0

Given:

"abc{defghij{kl}mnopqrst}uvwxyz{aaaaaaaaaa}"

I want to match the text between the characters { and the last } excluding nesting - i.e. the texts {defghij{kl}mnopqrst} and {aaaaaaaaaa}.

Without the nested {kl}, the regex expression \{[^{}]*\} works just fine. But not with the nested {kl}.

Is there a way to do this? If not possible, can I say "match text between { and } where the size of the enclosed text is at least, e.g. 3, characters so that the nested {kl} which contains two characters is not matched? (I'm assuming one level nesting)

Editor: https://www.freeformatter.com/java-regex-tester.html

Thanks,

cmutex
  • 1,478
  • 11
  • 24

1 Answers1

1

In your problem since nesting levels will not reach two, it is possible to solve it with a readable, short regex and that would be:

\{(?:\{[^{}]*}|[^{}]+)*}

In Java you have to escape opening braces, as I did.

Above regex matches an opening brace then looks for either something other than { and } characters (i.e. [^{}]+) or something enclosed in braces {[^{}]*} and repeats this pattern as much as possible then expects to match a closing brace.

See live demo here

revo
  • 47,783
  • 14
  • 74
  • 117