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

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

问题描述

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

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

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

里面有任意 key:"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天全站免登陆