You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中如何遍历正则捕获组的多个匹配结果

解决方案

你的问题根源在于正则没有启用全局匹配模式,且循环逻辑错误,导致每次都重复匹配第一个结果,最终进入死循环。以下是几种可行的修复方式:

方法1:修正正则与循环逻辑

给正则添加g(全局匹配)标志,这样exec()会自动推进匹配位置,直到找不到结果为止:

var imageList = [];

$.get('/custom/view/slideshow/images/', function(data) {
    var regEx = /\/images\/(.*\.png)">/ig; // 添加g全局匹配标志
    var item;
    
    // 循环直到exec返回null
    while ((item = regEx.exec(data)) !== null) {
        imageList.push(item[1]);
        console.log(imageList.length + "; " + item[1]);
    }
    
    // 输出结果
    imageList.forEach(img => console.log(img));
});

方法2:使用matchAll简化代码(ES6+)

matchAll可以直接返回所有匹配结果的迭代器,处理起来更简洁:

var imageList = [];

$.get('/custom/view/slideshow/images/', function(data) {
    // 遍历所有匹配项
    for (const match of data.matchAll(/\/images\/(.*\.png)">/ig)) {
        imageList.push(match[1]);
    }
    
    // 输出结果
    imageList.forEach(img => console.log(img));
});

甚至可以一行完成数组构建:

const imageList = [...data.matchAll(/\/images\/(.*\.png)">/ig)].map(match => match[1]);

方法3:更可靠的DOM解析(推荐)

用正则解析HTML容易受结构变化影响,直接通过DOM操作提取内容更鲁棒:

var imageList = [];

$.get('/custom/view/slideshow/images/', function(data) {
    // 创建临时容器加载HTML
    const tempContainer = document.createElement('div');
    tempContainer.innerHTML = data;
    
    // 选择所有文件链接
    const fileLinks = tempContainer.querySelectorAll('table.listing td.name a');
    
    fileLinks.forEach(link => {
        const href = link.getAttribute('href');
        // 筛选PNG文件并提取文件名
        if (href.endsWith('.png')) {
            imageList.push(href.split('/').pop());
        }
    });
    
    // 输出结果
    imageList.forEach(img => console.log(img));
});

内容的提问来源于stack exchange,提问作者amber

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 14:38:20