RegEx使用RegExp.exec从字符串中提取所有匹配项 [英] RegEx to extract all matches from string using RegExp.exec

查看:269
本文介绍了RegEx使用RegExp.exec从字符串中提取所有匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析以下类型的字符串:

I'm trying to parse the following kind of string:

[key:"val" key2:"val2"]

其中有任意键:"val"对.我想获取键名和值. 对于那些好奇的人,我试图解析任务战士的数据库格式.

where there are arbitrary key:"val" pairs inside. I want to grab the key name and the value. For those curious I'm trying to parse the database format of task warrior.

这是我的测试字符串:

[description:"aoeu" uuid:"123sth"]

旨在强调除空格外,任何内容都可以位于键或值中,冒号周围没有空格,并且值始终用双引号引起来.

which is meant to highlight that anything can be in a key or value aside from space, no spaces around the colons, and values are always in double quotes.

在节点中,这是我的输出:

In node, this is my output:

[deuteronomy][gatlin][~]$ node
> var re = /^\[(?:(.+?):"(.+?)"\s*)+\]$/g
> re.exec('[description:"aoeu" uuid:"123sth"]');
[ '[description:"aoeu" uuid:"123sth"]',
  'uuid',
  '123sth',
  index: 0,
  input: '[description:"aoeu" uuid:"123sth"]' ]

但是description:"aoeu"也与此模式匹配.如何找回所有比赛?

But description:"aoeu" also matches this pattern. How can I get all matches back?

推荐答案

继续循环调用re.exec(s)以获得所有匹配项:

Continue calling re.exec(s) in a loop to obtain all the matches:

var re = /\s*([^[:]+):\"([^"]+)"/g;
var s = '[description:"aoeu" uuid:"123sth"]';
var m;

do {
    m = re.exec(s);
    if (m) {
        console.log(m[1], m[2]);
    }
} while (m);

尝试使用此JSFiddle: https://jsfiddle.net/7yS2V/

Try it with this JSFiddle: https://jsfiddle.net/7yS2V/

这篇关于RegEx使用RegExp.exec从字符串中提取所有匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆