正则表达式:用嵌套元素替换字符串

时间:2019-03-16 20:45:51

标签: javascript

我有这个字符串:

const string = "{* * @test * { * username: {{username}} * email: {{email}} * password: {{password}} * name: { * first: {{firstname}} * last: {{lastname}} * }, * phone: {{phone}} * } }"

最后,我希望有这样的东西:

{
    "username": "{{username}}",
    "email": "{{email}}",
    "password": "{{password}}",
    "name": {
        "first": "{{firstname}}",
        "last": "{{lastname}}"
    },
    "phone": "{{phone}}"
}

这是我的代码:

    const str = "{* * @test * { * username: {{username}} * email: {{email}} * password: {{password}} * name: { * first: {{firstname}} * last: {{lastname}} * }, * phone: {{phone}} * } }"




    const regex = /.* \{ \* ([^:]+): ([^ ]+) \* } }/gm;
    const subst = `{\n\t"$1": "$2"\n}`;
    
    // The substituted value will be contained in the result variable
    const result = str.replace(regex, subst);
    
    console.log(result);

1 个答案:

答案 0 :(得分:2)

一种方法是替换所有无效的JSON令牌以生成有效的JSON字符串,然后使用JSON.parse将JSON字符串解析为对象。

如图所示,这有点困难,如果您在实际数据中还有其他边缘情况,则可能需要进行调整和优化,但是应该很好地处理递归结构问题。将其视为概念验证。

const string = "{* * @test * { * username: {{username}} * email: {{email}} * password: {{password}} * name: { * first: {{firstname}} * last: {{lastname}} * }, * phone: {{phone}} * } }";

const cleaned = string
  .replace(/({{.+?}})/g, `"$1"`)           // quote the template variables
  .replace(/ \* ([a-z]+?): /ig, ` "$1": `) // quote the keys
  .replace(/" "/g, `","`)                  // add commas between keys
  .replace(/\*/g, "")                      // remove asterisks
  .replace(/@[a-z]+/ig, "")                // get rid of the `@test`
  .trim()                                  // trim so we can rip off the `{}`s
;

const parsed = JSON.parse(cleaned.substr(1, cleaned.length - 2));

const expected = {
    "username": "{{username}}",
    "email": "{{email}}",
    "password": "{{password}}",
    "name": {
        "first": "{{firstname}}",
        "last": "{{lastname}}"
    },
    "phone": "{{phone}}"
};

console.log(
  `matches expected? ${JSON.stringify(expected) === JSON.stringify(parsed)}\n`, 
  parsed
);