gpt4 book ai didi

javascript - 正则表达式 : replace in string with nested elements

转载 作者:行者123 更新时间:2023-11-29 20:41:58 26 4
gpt4 key购买 nike

我有这个字符串:

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 - 正则表达式 : replace in string with nested elements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55201338/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com