猿问

缺少正则表达式以捕获最后一个键值列表条目

我有一个这样的字符串:

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)。知道如何使积极的前瞻可选吗?


慕沐林林
浏览 101回答 1
1回答

泛舟湖上清波郎朗

尝试使用正则表达式模式(\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然后,我们使用第一个捕获组作为键,第二个捕获组作为值来构建您预期的二维数组。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答