Regex to match words inside two or three curly braces

Viewed 537

I am writing a regular expression inside Kotlin app to match the following scenario: User will send string like this:

 1. "{{example}}" -> match: example 
 2. "{{{example2}}}" -> match: example2
 3. "{{example3}}}" -> do not match 
 4. "{example4}" -> do not match
 5. "{{{example5}}" -> do not match 
 6. "{{{{example6}}}}" -> do not match 
 7. "{{ example7 }}  some other words {{{example8}}}" -> match: example7 and example8 
 8. "{{{example9}}} some other words {{example10}} {{example11}}" -> match: example9, example10 and example 11

So to match only words between two or exactly three curly braces. This is the closest I got to my result:

regex = \{{2}([^{^}]+)\}{2}([^}])|\{{3}([^{^}]+)\}{3}([^}])

This matches everything fine except example5, you can also take a look here https://regex101.com/r/M0kw3j/1

2 Answers

Using alternation and lookarounds, you may use this regex:

(?<!\{)(\{{3}[^{}\n]*}{3}|\{{2}[^{}\n]*}{2})(?!})

Updated RegEx Demo

RegEx Details:

  • (?<!\{): Negative lookbehind to assert that we don't have { at the previous position
  • (: Start capture group #1
    • \{{3}: Match 3 opening {{{
    • [^{}\n]*: Match 0 or more of any character that are not { and }
    • }{3}: Match 3 closing }}}
    • |: OR (alternation)
    • \{{2}: Match 2 opening {{
    • [^{}\n]*: Match 0 or more of any character that are not { and }
    • }{2}: Match 2 closing }}
  • ): Close capture group #1
  • (?!}): Negative lookahead to assert that we don't have } at the next position

Here is something that might work for you:

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

See the online demo

  • Words that are between exactly 2 curly brackets will be in group 1.
  • Words that are between exactly 3 curly brackets will be in group 2.

  • (?<!\{) - Negative lookbehind for opening curly bracket.
  • \{\{ - Two literal curly (opening) brackets.
  • (?: - Open non-capture group.
    • ([^{}]+) - A 1st capture group holding 1+ non-opening/closing brackets.
    • | - Or:
    • \{([^{}]+)} - A 2nd capture group with leading and trailing brackets.
    • ) - Close non-capture group.
  • }} - Two literal curly (closing) brackets.
  • (?!}) - Negative lookahead for closing curly bracket.
Related