4

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.

mrzasa
  • 22,895
  • 11
  • 56
  • 94
Panczo
  • 424
  • 5
  • 20

2 Answers2

6

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 {
ctwheels
  • 21,901
  • 9
  • 42
  • 77
3

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.

O.O.Balance
  • 2,930
  • 5
  • 23
  • 35
  • 2
    `.*` will give incorrect results if two `{}` exist in the same string. See it working incorrectly [here](https://regex101.com/r/ig9rrW/2) – ctwheels Mar 23 '18 at 15:21
  • 1
    @ctwheels Thanks for pointing that out. Changed to `.*?`. https://regex101.com/r/5gA4Ji/1 – O.O.Balance Mar 23 '18 at 15:28