如何使用嵌套花括号在双花括号之间提取内容

问题描述 投票:1回答:1

我想解析字符串并得到这样的匹配:

var string = `{{type|equal:'user','This is a {{type}}','{{type}} not authorized to perform "{{current_action}}" action'}}`;

期望的输出:

[
    {
        match: '{{type|equal:'user','This is a {{type}}','{{type}} not authorized to perform "{{current_action}}" action'}}',
        key: 'type',
    },
    {
        match: '{{type}}',
        key: 'type'
    },
    {
        match: '{{current_action}}',
        key: 'current_action'
    }
]

这是我尝试过的:

var string = `{{type|equal:'user','This is a {{type}}','{{type}} not authorized to perform "{{current_action}}" action'}}`;
var regex = RegExp('{{(.*?)}}', 'g');
var match;
var matches = [];

while ((match = regex.exec(string)) !== null) {
    matches.push({match: match[0], key: match[1]});
}

console.log(matches);
javascript string parsing
1个回答
0
投票

尝试像https://regex101.com/一样的smth

像下面的东西应该工作

var matches = string.match(/{{\w+}}/g)
© www.soinside.com 2019 - 2024. All rights reserved.