如何在JavaScript中检索正则表达式的所有匹配项? [英] How do I retrieve all matches for a regular expression in JavaScript?

查看:208
本文介绍了如何在JavaScript中检索正则表达式的所有匹配项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是正则表达式的新手。我正在尝试解析以下类型的字符串:

I am new to regular expressions. I'm trying to parse the following kind of string:

[key:valkey2: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. Here is my test string:

[描述:aoeuuuid:123sth] 这意味着突出显示除了空格之外的任何东西都可以在键或值中,冒号周围没有空格,值总是用双引号。在节点中,这是我的输出:

[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"]' ]

但是说明: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: http://jsfiddle.net/7yS2V/

Try it with this jsfiddle: http://jsfiddle.net/7yS2V/

这篇关于如何在JavaScript中检索正则表达式的所有匹配项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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