在 javascript 正则表达式中否定并重复原子组

Vit*_*.us 1 javascript regex

我需要

  • 匹配{{
  • 启动捕获组
  • 任何不是的东西}}
  • 结束捕获
  • 匹配}}

样本:

dummy text
{{ text to be matched }}
more dummy text dummy
dummy {{ foo { bar }} dummy text
dummy text
{{}}}
Run Code Online (Sandbox Code Playgroud)

结果:

比赛1:{{ text to be matched }}

第 0 组:text to be matched

比赛2:{{ foo { bar }}

第 0 组:foo { bar

比赛3:{{}}}

第 0 组:}

我遇到的问题是not }}因为 Javascript 没有原子组。

我不能否定非捕获组并像这样重复它

{{                  match {{
    (               capture
        ^(?:}})+    not "}}" 1+ times 
    )               end capture
}}                  match }}
Run Code Online (Sandbox Code Playgroud)

/{{(.+)}}/有点有效,但前提是我没有换行符。

Cas*_*yte 5

为了满足您的要求,您可以使用以下模式:

{{([^}]*(?:}[^}]+)*}*)}}
Run Code Online (Sandbox Code Playgroud)

细节:

{{
(
    [^}]*         # all that is not a closing bracket
    (?:
        }[^}]+    # a closing bracket followed by at least one other character
    )*
    }*            # eventual closing brackets at the end
)
}}
Run Code Online (Sandbox Code Playgroud)

另一种方式(更短但效率较低):

{{([^]*?)}}(?!})
Run Code Online (Sandbox Code Playgroud)

注意:该问题与原子团无关。