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

如何从字符串集合提取仅含*的通配符字符串?(优先NodeJS)

从字符串集合提取单通配符(*)模式的方案

核心算法思路

这种需求本质是提取字符串集合的最长公共前后缀,再用*替换中间不一致的部分,步骤如下:

  1. 将所有输入字符串按空格分割为单词数组(按单词粒度匹配,而非字符级);
  2. 遍历比对所有字符串的前缀,找到最长的连续公共单词序列,作为模式前缀;
  3. 反向遍历比对所有字符串的后缀,找到最长的连续公共单词序列,作为模式后缀;
  4. 拼接前缀、*、后缀得到最终通配符模式;若所有字符串完全一致则直接返回原字符串,无公共部分则返回*。

NodeJS实现方式

自定义实现代码

直接实现上述逻辑,可控性强,适配你的需求:

function extractWildcardPattern(strings) {
  if (strings.length === 0) return '';
  if (strings.length === 1) return strings[0];

  // 按空格分割为单词数组,处理多余空格
  const wordLists = strings.map(s => s.trim().split(/\s+/));
  const referenceWords = wordLists[0];
  let prefixLength = 0;

  // 确定最长公共前缀的单词数量
  while (prefixLength < referenceWords.length) {
    const currentWord = referenceWords[prefixLength];
    if (wordLists.every(words => words[prefixLength] === currentWord)) {
      prefixLength++;
    } else {
      break;
    }
  }

  // 确定最长公共后缀的单词数量
  let suffixLength = 0;
  const maxPossibleSuffix = Math.min(...wordLists.map(words => words.length)) - prefixLength;
  while (suffixLength < maxPossibleSuffix) {
    const currentWord = referenceWords[referenceWords.length - 1 - suffixLength];
    if (wordLists.every(words => words[words.length - 1 - suffixLength] === currentWord)) {
      suffixLength++;
    } else {
      break;
    }
  }

  const prefix = referenceWords.slice(0, prefixLength).join(' ');
  const suffix = referenceWords.slice(-suffixLength).join(' ');

  // 拼接结果
  if (prefix && suffix) {
    return `${prefix} * ${suffix}`;
  } else if (prefix) {
    return `${prefix} *`;
  } else if (suffix) {
    return `* ${suffix}`;
  } else {
    return '*';
  }
}

// 测试示例输入
const inputStrings = [
  "apple pie is not too so good",
  "apple pie is not so good",
  "apple pie is too good"
];
console.log(extractWildcardPattern(inputStrings)); // 输出: apple pie is * good

现有库辅助

  • string-similarity:可辅助计算字符串或单词序列的相似度,帮助快速定位公共前后缀,但仍需自行封装为通配符模式生成逻辑;
  • 注意:多数通用通配符库(如wildcard-match)侧重匹配而非生成模式,因此自定义实现更贴合你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 21:12:19