javascript - 解析模板化字符串
问题描述
我有一个这样的字符串
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
根据解析格式的正则表达式将这些对转换为所需的对象map("")to("")
格式。最后,null
s 被过滤掉。
推荐阅读
- azure-functions - Azure Functions 未在本地创建 Azure 表列
- .net - 安装 dropbox api nuget 包时出错
- java - 如何创建具有多个“级别”的 Spring Boot API
- javascript - 为什么发送单个参数的函数调用会突然收到整个元素?
- javascript - react-socks 不能通过我的图标立即工作
- python - 修复 422 响应 python 请求获取
- r - R函数用任何整数替换字符
- android-studio - 使用 DragLinearLayout 时如何获取子位置
- python - 使用多边形坐标将带注释的图像转换为二进制蒙版图像
- gitlab - 尝试从 GitLab 将自定义 Helm 存储库添加到本地时出错