Regex match everything between two {}

跟風遠走 提交于 2019-12-07 11:41:48

问题


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.


回答1:


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 {



回答2:


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.



来源:https://stackoverflow.com/questions/49452796/regex-match-everything-between-two

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!