Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex match everything between two {}

I was looking at different answers here but unfortunately none of them was good for my case. So I hope you don't mind about it.

So I need to match everything between two curly brackets {} except situation when match starts with @ and without these curly brackets e.g:

  1. "This is a super text {match_this}"
  2. "{match_this}"
  3. "This is another example @{deal_with_it}"

Here are my test strings, 1,2,3 are valid while the last one shouldn't be:

  1   {eww}
  2   r23r23{fetwe}
  3   #{d2dded}
  4   @{d2dded}

I was trying with:

(?<=[^@]\{)[^\}]*(?=\})

Then only 2th and 3th options were matches (without the first one) https://regex101.com/r/qRInUf/2/

Then I was trying:

\{(.*?)\} or [^@]\{(.*?)\}

In both cases I was unable to match 1,2,3 values https://regex101.com/r/uYRtLD/1

Thanks in advance for any suggestions.

EDIT: This is for java.

like image 657
Panczo Avatar asked Jan 03 '23 15:01

Panczo


2 Answers

See regex in use here

(?<=(?<!@)\{)[^}]*(?=})
  • (?<=(?<!@)\{) Positive lookbehind ensuring what precedes matches the following
    • (?<!@) Negative lookbehind ensuring what precedes doesn't match @ literally
    • \{ Match { literally.
  • [^}]* Matches any character except } any number of times
  • (?=}) Positive lookahead ensuring what follows is } literally

Results:

{eww}           # Matches eww
r23r23{fetwe}   # Matches fetwe
#{d2dded}       # Matches d2dded
@{d2dded}       # Does not match this because @ precedes {
like image 187
ctwheels Avatar answered Jan 05 '23 17:01

ctwheels


Use this regex:

(?<!@\{)(?<=\{).*?(?=\})

A negative lookbehind to assure no @{, a positive lookbehind to assure a { and a positive lookahead to assure a }.

Try it online here.

like image 29
O.O.Balance Avatar answered Jan 05 '23 17:01

O.O.Balance