我有一个这样的字符串
const str = 'map("a")to("b");map("foo")to("bar");map("alpha")to("beta");'
我想解析这个字符串以生成类似 json 的东西
[{id: 'a', map: 'b'},
{id: 'foo', map: 'bar'},
{id: 'alpha', map: 'beta'}]
我想知道正则表达式是否是执行此操作的最佳方式,或者是否有任何我可以利用的实用程序库
最佳答案
这是适用于您当前情况的正则表达式:
const str = 'map("a")to("b");map("foo")to("bar");map("alpha")to("beta");';
const res = str.split(";").map(e => {
const k = e.match(/map\("(.+?)"\)to\("(.+?)"\)/);
return k && k.length === 3 ? {id: k[1], map: k[2]} : null;
}).filter(e => e);
console.log(res);
想法是拆分分号(当分号是所需键/值的一部分时,可以使用环视来处理情况),然后根据解析 map("")to("")
格式的正则表达式。最后,过滤掉 null
。
关于javascript - 解析模板字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52194109/