简体   繁体   English

正则表达式匹配两个{}之间的所有内容

[英]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 eg: 所以我需要匹配两个大括号{}之间的所有内容,除了匹配以@开头且没有这些大括号的情况,例如:

  1. "This is a super text { match_this }" “这是一个超级文本{ match_this }”
  2. "{ match_this }" “{ match_this }”
  3. "This is another example @{deal_with_it}" “这是另一个例子@ {deal_with_it}”

Here are my test strings, 1,2,3 are valid while the last one shouldn't be: 这是我的测试字符串,1,2,3有效,而最后一个不应该是:

  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/ 然后只有第2和第3个选项匹配(没有第一个) 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 在这两种情况下,我都无法匹配1,2,3值https://regex101.com/r/uYRtLD/1

Thanks in advance for any suggestions. 在此先感谢您的任何建议。

EDIT: This is for java. 编辑:这是为java。

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 {

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 . 在这里尝试一下

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM