正则表达式:嵌套组中的惰性匹配

Regex: Lazy matching in nested groups

我有这个正则表达式:/{(?:{(?:.*?)?)?$/g

请注意,我正在尝试在最里面的组中延迟匹配 .*?

但它的行为与我预期的不同:

const regex = /{(?:{(?:.*?)?)?$/g;

let match = "{{abc{".match(regex)
// expected: [ "{" ]
// actual: [ "{{abc{" ]

match = "{{abc{{".match(regex)
// expected: [ "{{" ]
// actual: [ "{{abc{{" ]

match = "{{abc{{def".match(regex)
// expected: [ "{{def" ]
// actual: [ "{{abc{{def" ]

我正在使用此正则表达式来匹配 {{{{{something,如果它位于字符串的末尾(不考虑多行字符串)

可能是因为字符串是从左到右匹配的,但是有没有一种优雅的方式来获得预期的行为?




编辑:

在选定的解决方案中使用正则表达式解决了上述问题,但如果最后一个 {{ 之后的字符串包含一个或多个 { 不相互跟随,则会失败。

示例:

const regex = /{(?:{(?:[^{]*?)?)?$/g;

let match = "{{abc{{de{f".match(regex)
// expected: [ "{{de{f" ]
// actual: null

match = "{{abc{{de{f{g".match(regex)
// expected: [ "{{de{f{g" ]
// actual: null

使用 .*,您匹配所有内容,包括 {。您必须使用 [^{] 从 "innermost string" 中排除它,并且您可以在此处添加您还想排除的任何字符:

{(?:{(?:[^{]*?)?)?$

检查一下here

对于编辑,您需要将 { 中的一个设为可选,以便能够同时解析 {{{

{(?:{?(?:[^{]*?)?)?$.

检查一下here