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
Here is something that might work for you:
(?<!\{)\{\{(?:([^{}]+)|\{([^{}]+)})}}(?!})
See the online demo
(?<!\{)
- 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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With