首页 > 解决方案 > 解析模板化字符串

问题描述

我有一个这样的字符串

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'}]

我想知道正则表达式是否是最好的方法,或者是否有任何我可以利用的实用程序库

标签: javascriptjsonregexstringparsing

解决方案


这是一个适用于您当前情况的正则表达式:

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根据解析格式的正则表达式将这些对转换为所需的对象map("")to("")格式。最后,nulls 被过滤掉。


推荐阅读