我试图解析以下类型的字符串:
[key:"val" key2:"val2"]
其中有任意键:“val”对在里面。我想获取键名和值。
对于那些好奇的人,我试图解析任务战士的数据库格式。
这是我的测试字符串:
[description:"aoeu" uuid:"123sth"]
这意味着除了空格之外,任何东西都可以放在键或值中,冒号周围没有空格,值总是在双引号中。
在node中,这是我的输出:
[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”也符合这个模式。我怎么能得到所有的比赛回来?
如果你能够使用matchAll,这里有一个技巧:
数组中。From有一个“选择器”参数,这样你就不会得到一个尴尬的“匹配”结果数组,你可以把它投射到你真正需要的东西上:
Array.from(str.matchAll(regexp), m => m[0]);
如果你已经命名了组。(/(?<firstname>[a-z][a-z] +)/g)你可以这样做:
Array.from(str.matchAll(regexp), m => m.groups.firstName);
可迭代对象更好:
const matches = (text, pattern) => ({
[Symbol.iterator]: function * () {
const clone = new RegExp(pattern.source, pattern.flags);
let match = null;
do {
match = clone.exec(text);
if (match) {
yield match;
}
} while (match);
}
});
循环中的用法:
for (const match of matches('abcdefabcdef', /ab/g)) {
console.log(match);
}
或者如果你想要一个数组:
[ ...matches('abcdefabcdef', /ab/g) ]