Javascript正则表达式所有匹配

Javascript regex all matches

本文关键字:正则表达式 Javascript      更新时间:2023-09-26

我试图通过regex在我的源中找到一些东西,但我不能让它返回我需要的所有数据。我使用的正则表达式我已经在regex101上测试过了,我认为它工作得很好。

我的来源:

/**
 * @author person1
 * @author person2
 */
console.log('a');

我想要检索person1和person2。

我代码:

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);
            });
        }
    });

运行时,只返回person1而不是person2。我的正则表达式是错的还是我错过了什么?

RegExp对象是有状态的,并保留最新匹配的索引,以便从那里继续。因此,您可能希望在循环中多次运行regex。

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

您也可以使用data.match(...),但这不会提取匹配组

现在你可以使用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);