doufang3001 2015-12-15 00:45
浏览 48
已采纳

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

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

  • 写回答

1条回答 默认 最新

  • dpiz9879 2015-12-15 00:59
    关注

    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'.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部