我有一个这样的字符串:a=func(1, 2, 2), b='hey', c=foobar('text'), d=1我想解析成它的键值组件,以便我可以获得一个列表[['a', 'func(1, 2, 2)', ['b', '\'hey\''], ['c', 'foobar(\'text\')'], ['d', '1']]我的方法是使用这个正则表达式:(\w*) *= *([^=]*), (?=\w* *=)积极向前看,但这忽略了最后一个键值对 ( d=1)。知道如何使积极的前瞻可选吗?
1 回答

泛舟湖上清波郎朗
TA贡献1818条经验 获得超3个赞
尝试使用正则表达式模式(\w+)=(.*?)(?:,\s*(?=\w+=)|$),然后捕获所有匹配项:
var input = "a=func(1, 2, 2), b='hey', c=foobar('text'), d=1";
var regex = /(\w+)=(.*?)(?:,\s*(?=\w+=)|$)/g;
var match = regex.exec(input);
var result = [];
while (match != null) {
result.push(new Array(match[1], match[2]));
match = regex.exec(input);
}
console.log(result);
这是模式的作用:
(\w+) match AND capture a key
= match an =
(.*?) then match AND capture anything, until we see
(?:,\s*(?=\w+=)|$) a comma, followed by optional space, and the next key
OR the end of the input string
然后,我们使用第一个捕获组作为键,第二个捕获组作为值来构建您预期的二维数组。
添加回答
举报
0/150
提交
取消