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

基于通配符的分页URL生成算法咨询(支持多通配符段)

问题:根据通配符数据生成所有可能的URL列表

给定URL模板:

website.com/news/*1/*2/

以及包含通配符对应数组的对象:

{
  "*1": ['april', 'may', 'june'],
  "*2": [28, 29, 30],
}

需要生成所有替换通配符后的URL列表,预期结果为:

website.com/news/april/28/
website.com/news/april/29/
website.com/news/april/30/
website.com/news/may/28/
website.com/news/may/29/
website.com/news/may/30/
website.com/news/june/28/
website.com/news/june/29/
website.com/news/june/30/

已知URL总数为各通配符数组长度的乘积,但无法写出适配**通配符数量不固定(范围1到n)**的算法。


解决方案

核心思路是计算所有通配符对应数组的笛卡尔积(即所有可能的元素组合),再将每组组合依次替换到URL模板的对应位置。

以下是JavaScript实现示例:

// 计算笛卡尔积的工具函数
function cartesianProduct(arrays) {
  return arrays.reduce((acc, curr) => {
    return acc.flatMap(prev => curr.map(item => [...prev, item]));
  }, [[]]);
}

// 生成所有URL的核心函数
function generateAllUrls(urlTemplate, wildcardData) {
  // 提取模板中的所有通配符(匹配*数字格式)
  const wildcards = urlTemplate.match(/\*\d+/g) || [];
  // 按模板顺序获取对应数组
  const targetArrays = wildcards.map(wildcard => wildcardData[wildcard]);
  // 生成所有元素组合
  const combinations = cartesianProduct(targetArrays);
  // 替换组合到模板生成URL
  return combinations.map(combination => {
    let url = urlTemplate;
    wildcards.forEach((wc, idx) => {
      url = url.replace(wc, combination[idx]);
    });
    return url;
  });
}

// 测试示例
const template = 'website.com/news/*1/*2/';
const data = {
  '*1': ['april', 'may', 'june'],
  '*2': [28, 29, 30],
};

const allUrls = generateAllUrls(template, data);
console.log(allUrls.join('\n'));

关键说明:

  • 笛卡尔积计算:通过cartesianProduct函数实现,能处理任意数量的输入数组,输出所有可能的元素组合;
  • 通配符适配:通过正则提取模板中的通配符,保证替换顺序和模板中出现的顺序一致;
  • 扩展性:支持1到n个通配符的场景,只要通配符名称与wildcardData中的键完全匹配即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 20:15:38