简体   繁体   English

Javascript 正则表达式所有匹配项

[英]Javascript regex all matches

I'm trying to find a couple things in my source through regex, but I can't get it to returns all the data I need.我试图通过正则表达式在我的源中找到一些东西,但我无法让它返回我需要的所有数据。 The regex I use I've tested it on regex101 and works just fine I think.我使用的正则表达式我已经在regex101上测试过,我认为它工作得很好。

My source:我的来源:

/**
 * @author person1
 * @author person2
 */

console.log('a');

What I want is to retrieve person1 and person2.我想要的是检索person1和person2。

My code:我的代码:

fs.readdir('./src', function (err, files) {
        for (var i = 0; i < files.length; i++ ) {
            var file = files[i];

            fs.readFile('./src/' + file, { encoding: 'utf-8' }, function (err, data) {
                if (err)
                    throw err;

                var matches = (/@author (.*)$/gm).exec(data);
                console.log(matches);
            });
        }
    });

When ran this only returns person1 not person2.运行时只返回 person1 而不是 person2。 Is my regex wrong or what am I missing?我的正则表达式错了还是我错过了什么?

A RegExp object is stateful, and retains the index of the latest match, to continue from there. RegExp 对象是有状态的,并保留最新匹配项的索引,以从那里继续。 Thus, you may want to run the regex several times in a loop.因此,您可能希望在循环中多次运行正则表达式。

var match, authors = [];
var r = /@author (.*)$/gm;
while(match = r.exec(data)) {
        authors.push(match[1]);
}

You can also use data.match(...) , but this won't extract the match groups.您也可以使用data.match(...) ,但这不会提取匹配组。

Now a days you can use String.prototype.matchAll现在你可以使用String.prototype.matchAll

 const s = ` /** * @author person1 * @author person2 */ console.log('a'); `; const re = /@author\\s+(.*)$/gm; const people = [...s.matchAll(re)].map(m => m[1]); console.log(people);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM