【问题标题】:Parsing a templated string解析模板化字符串
【发布时间】:2018-09-05 22:23:07
【问题描述】:

我有一个这样的字符串

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

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

【问题讨论】:

    标签: javascript json regex string parsing


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      我很确定有一个不错的正则表达式解决方案,它更短更快,但由于我不擅长正则表达式,所以我解决了这样的问题:

      const str = 'map("a")to("b");map("foo")to("bar");map("alpha")to("beta");'
      
      const result = str.split(';').map(e => {
      
        const parts = e.substring(3).split('to').map(item => item.replace(/\W/g, ''));
      
        return {
          id: parts[0],
          map: parts[1]
        };
      })
      console.log(result);
      

      【讨论】:

      • 只需要切掉拆分中的最后一个元素...否则结果[3]是{id: "", map: undefined}
      猜你喜欢
      • 2015-11-11
      • 2013-08-28
      • 2020-02-24
      • 2022-01-04
      • 2017-03-01
      • 1970-01-01
      • 2013-07-09
      • 1970-01-01
      • 2015-03-31
      相关资源
      最近更新 更多