当前位置: 代码迷 >> JavaScript >> Javascript 正则表达式所有匹配项
  详细解决方案

Javascript 正则表达式所有匹配项

热度:104   发布时间:2023-06-07 16:40:54.0

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

我的来源:

/**
 * @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 对象是有状态的,并保留最新匹配项的索引,以从那里继续。 因此,您可能希望在循环中多次运行正则表达式。

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

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

现在你可以使用

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