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

如何根据原字符串的匹配顺序重新排序指定子串集合?

解决方案

要实现将c中的子串按照它们在a中被匹配到的顺序重新排列输出,可按以下逻辑实现:

实现思路

  • 先将a和c按分隔符b拆分为数组
  • 遍历a的每个元素,从中筛选出属于c的子串,同时记录已匹配的子串避免重复
  • 最终将匹配到的子串按首次出现顺序用b拼接

具体代码

const a = "excel|side|home|door";
const b = "|";
const c = "or|de|el";

const aSegments = a.split(b);
const cSubstrings = c.split(b);
const resultList = [];
const usedSubstrings = new Set();

// 按a的顺序查找匹配的c子串
aSegments.forEach(segment => {
  cSubstrings.forEach(sub => {
    if (segment.includes(sub) && !usedSubstrings.has(sub)) {
      resultList.push(sub);
      usedSubstrings.add(sub);
    }
  });
});

const finalResult = resultList.join(b);
console.log(finalResult); // 输出: el|de|or

代码解释

  • 使用Set存储已匹配的子串,确保每个子串仅被添加一次,避免重复输出
  • 遍历顺序优先遵循a中元素的顺序,再检查元素是否包含c的子串,保证结果顺序是子串在a中首次出现的顺序
  • 如果a多个元素包含同一个c子串,只会保留第一次匹配时的顺序

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 18:55:10