【问题标题】:How to extract content between double curly braces with nested curly braces如何使用嵌套花括号提取双花括号之间的内容
【发布时间】:2019-02-07 10:19:53
【问题描述】:

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

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】:

试试https://regex101.com/

类似下面的东西应该可以工作

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

【讨论】:

  • 它没有给出想要的输出。
猜你喜欢
  • 2018-10-12
  • 2011-01-12
  • 1970-01-01
  • 2019-01-26
  • 2021-10-13
  • 1970-01-01
  • 2013-04-21
  • 2017-01-15
相关资源
最近更新 更多