我有这个字符串:

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

最佳答案

一种方法是替换所有无效的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
);

关于javascript - 正则表达式:用嵌套元素替换字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55201338/

10-11 22:05
查看更多