Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match words inside two or three curly braces

Tags:

java

regex

kotlin

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

like image 808
Aldin Muratovic Avatar asked Dec 23 '22 15:12

Aldin Muratovic


1 Answers

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.
like image 179
JvdV Avatar answered Jan 05 '23 13:01

JvdV