正则表达式 - 数字括号问题

I have some big trouble for this allowing this Regex :

                               {{{ hello{{there}} }}}

My problem is essentially to distinguish between double and triple brackets since the notation use a braket... I have tried

\{{2}           /*Accept only two brakets --- Does NOT work*/

to allow 2 brakets but it does no work at all.

Is a Regex specialist can tell me a trick ? Thanks in advance

To discriminate between triple and double braces you need to use lookarounds.

To only match double opening braces, use

(?<!{){{2}(?!{)

Here, (?<!{) is a negative lookbehind that makes sure there is no { before the first { and (?!{) is a negative lookahead that makes sure there is no { after the second {. See regex demo here.

To only match triple opening braces use

(?<!{){{3}(?!{)

See another regex demo

Just use } in all the above expressions to match closing braces.

Note that there is no need to escape { and } in PHP regex, the engine is smart enough to know they are not part of the limiting quantifier.

To get all substrings between {{{ and }}}, you can use

'~(?<!{){{{(?!{)\s*(.*?)\s*(?<!})}}}(?!})~s'

See the 3rd regex demo. PHP code:

$re = '~(?<!{){{{(?!{)\s*(.*?)\s*(?<!})}}}(?!})~s'; 
$str = "{{{ hello{{there}} }}} {{{good {{morning}} }}}"; 
preg_match_all($re, $str, $matches);
print_r($matches[1]);

Output:

[0] => hello{{there}}
[1] => good {{morning}}

Also note that in case you have no quadruple {s and }s, you can omit the lookarounds and use '~{{{\s*(.*?)\s*}}}~s'.