javascript - 带有正则表达式的 Javascript 以不同的特定字符拆分字符串
问题描述
我有以下字符串
Name=(Last, First), Age=(31 year, 6 months, 3 day), Height= 6.1 ft, Employment=None, Email Address =/NA/, Mobile=XXXX
我想将它们拆分为以下内容以构建字典
Name: "(Last, First)"
Age: "(31 year, 6 months, 3 day)"
Height: " 6.1 ft"
...
我遇到了这篇文章并尝试对其进行调整,但可以使用带/不带“()”的键使其工作。这是代码或来自此链接。感谢您的帮助,并随时提出更简单或替代的方法。
txt="Name=(Last, First), Age=(31 year, 6 months, 3 day), Height= 6.1 ft, Employment=None, Email Address =/NA/, Mobile=XXXX"
//var r = /.+?=.+?(?=(\([^)]+\),)|(.=)|$)/g;
//var r = /.+?=.+?(?=(=(.*),)|$)/g;
var r = /.+?=.+?(?=(\),)|(\d\b,)|$)/g;
var obj = txt.match(r).reduce(function(obj, match) {
var keyValue = match.split("=");
obj[keyValue[0].replace(/,\s/g, '')] = keyValue[1];
return obj;
}, {});
console.log(obj);
解决方案
要匹配属性和值,您可以使用:
(\w+)\s*=\s*(\([^)]+\)|[^,]+)
(\w+)
- 匹配并捕获属性(一个或多个单词字符)\s*=\s*
- 后跟可选空格、a=
和更多可选空格(\([^)]+\)|[^,]+)
- 匹配并捕获:\([^)]+\)
- A(
,后接非)
字符,后接)
, 或[^,]+
- 非逗号字符
const str = 'Name=(Last, First), Age=(31 year, 6 months, 3 day), Height= 6.1 ft, Employment=None, Email Address =/NA/, Mobile=XXXX';
const obj = {};
for (const [, prop, val] of str.matchAll(/(\w+)\s*=\s*(\([^)]+\)|[^,]+)/g)) {
obj[prop] = val;
}
console.log(obj);
如果输入键也可能包含空格,则匹配除 a 之外的任何内容=
:
const str = 'Employee Name=(Last, First), Person Age=(31 year, 6 months, 3 day), Height= 6.1 ft, Employment=None, Email Address =/NA/, Mobile=XXXX';
const obj = {};
for (const [, prop, val] of str.matchAll(/(\w[^=]+)\s*=\s*(\([^)]+\)|[^,]+)/g)) {
obj[prop] = val;
}
console.log(obj);
如果您不能使用matchAll
,则使用 手动迭代匹配项exec
:
const str = 'Name=(Last, First), Age=(31 year, 6 months, 3 day), Height= 6.1 ft, Employment=None, Email Address =/NA/, Mobile=XXXX';
const obj = {};
const pattern = /(\w+)\s*=\s*(\([^)]+\)|[^,]+)/g;
let match;
while (match = pattern.exec(str)) {
const [, prop, val] = match;
obj[prop] = val;
}
console.log(obj);
推荐阅读
- vb.net - 在 vb.NET 中的一行代码中打断注释
- python-3.x - 如何在双 x 轴和 y 轴上格式化小刻度,这两个轴都是对数缩放的?
- php - 如何根据id获取国家名称?
- authentication - 我们可以将 ADFS 配置为 Azure 的令牌端点吗
- php - 如何通过电子邮件 Laravel PHP 从表中发送 JSON 数据(已经成功发送输入字段)
- swagger - 如何将 OpenAPI 2.0 转换为 OpenAPI 3.0?
- c# - 如何使用 Fluent Assertions 引发异常?
- javascript - AND 多个参数
- kubernetes - 从服务内启动 Kubernetes 作业
- r - 如何从 html 的 href 链接登陆比特流 url