为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕沐林林 2021-06-02 22:29:02
我有一个这样的字符串: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

然后,我们使用第一个捕获组作为键,第二个捕获组作为值来构建您预期的二维数组。


查看完整回答
反对 回复 2021-06-03
  • 1 回答
  • 0 关注
  • 100 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信