首页 > 解决方案 > 带有正则表达式的 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);

标签: javascriptregex

解决方案


要匹配属性和值,您可以使用:

(\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);


推荐阅读