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

时间:2018-09-01 19:23:44

标签: javascript string parsing

我想解析字符串并获得匹配,如下所示:

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);

1 个答案:

答案 0 :(得分:0)

尝试像https://regex101.com/

如下所示的方法应该起作用     

var matches = string.match(/{{\w+}}/g)