简体   繁体   English

正则表达式以查找3个方括号之间包含的字符串

[英]Regular Expression to find a string included between 3 brackets

Could give a hand with this regex ? 可以帮忙这个正则表达式吗?

\{{{(.*?)\}}}

It matches 它匹配

{{{test1}}}
{{{{test4}}}
{{{test5}}}

I would like to match only {{{test1}}} and {{{test5}}} . 我只想匹配{{{test1}}}{{{test5}}} There must be only 3 brackets on the left and right no, so {{{{test4}}} should be INVALID. 左边和右边必须只有3个方括号,因此{{{{test4}}}应该是无效的。

You need to restrict the delimiters with lookarounds: 您需要使用环顾四周来限制定界符:

(?<!{){{{(?!{)(.*?)(?<!})}}}(?!})
^^^^^^    ^^^^      ^^^^^   ^^^^^

See the regex demo 正则表达式演示

The (?<!{) is a negative lookbehind that fails the match if there is a { immediately to the left of the current location and (?!{) is a negative lookahead that fails the match immediately to the right of the current location. (?<!{)是负回顾后失败的比赛,如果有一个{立即到当前位置和左边(?!{)是负先行立即失败,比赛进行到当前位置的右。 Similar constructs are used to set the context for the }}} trailing delimiter. 类似的构造用于设置}}}尾随定界符的上下文。

To exclude matching {{{....}}} substrings that contain either { or } , you need to replace the .*? 要排除匹配{{{....}}}包含子要么 {} ,则需要更换.*? (lazy dot matching pattern) with a *negated character class [^{}]* that will also make the (?!{) and (?<!{) lookarounds redundant in the above regex: (负点匹配模式)具有*否定的字符类[^{}]* ,这也会使(?!{)(?<!{)环顾四周在上述正则表达式中变得多余:

(?<!{){{{([^{}]*)}}}(?!})

See another regex demo , where {{{test{6}here}}} is not matched. 请参见另一个regex演示 ,其中{{{test{6}here}}}不匹配。

Usage to extract the values in between {{{ and }}} : 用于提取{{{}}}之间的值的用法:

var results = Regex.Matches(s, @"(?<!{){{{([^{}]*)}}}(?!})")
    .Cast<Match>()
    .Select(m => m.Groups[1].Value)
    .ToList();

You can use this one : (?<!{){{3}[^{}]*}{3}(?!}) 您可以使用以下命令: (?<!{){{3}[^{}]*}{3}(?!})

Explanation 说明

{{3} starts with a { 3 times exactly {{3}{的 3倍开头

[^{}]* any character except { or } [^{}]* {或} 外的任何字符

}{3} ends with } 3 times exactly }{3}结尾} 3倍恰好

Surrounded by negative lookbehind (?<!{) and negative lookahead (?!}) to make sure that the immediate preceding character will not be { and that the next immediate character will not be } 由负向后查找(?<!{)和负向前查找(?!})包围,以确保前一个字符不会是{,下一个字符不会是}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM