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

如何用正则表达式过滤数组并按匹配度从高到低排序?

按正则匹配度对过滤后的数组排序

现有数组:

const arr = ["another world", "foo", "bar", "foo-another-bar", "another"]

使用正则/another/过滤数组的代码如下,过滤后得到结果[ 'another world', 'foo-another-bar', 'another' ]:

const reg = new RegExp(/another/)
const filteredArr = arr.filter(item => item.match(reg))

需要将上述filteredArr按匹配度从高到低排序,期望结果为['another', 'another world', 'foo-another-bar']。

实现方案

通过自定义排序逻辑,从完全匹配、匹配位置、内容占比三个维度判断匹配度,代码如下:

const reg = /another/;
const arr = ["another world", "foo", "bar", "foo-another-bar", "another"];
const filteredArr = arr.filter(item => reg.test(item));

// 按匹配度从高到低排序
const sortedArr = filteredArr.sort((a, b) => {
  // 完全匹配的项优先排在最前面
  const aExactMatch = a === reg.source;
  const bExactMatch = b === reg.source;
  if (aExactMatch && !bExactMatch) return -1;
  if (!aExactMatch && bExactMatch) return 1;

  // 匹配子串出现位置越靠前,优先级越高
  const aMatchIndex = a.indexOf(reg.source);
  const bMatchIndex = b.indexOf(reg.source);
  if (aMatchIndex !== bMatchIndex) {
    return aMatchIndex - bMatchIndex;
  }

  // 字符串越短,匹配内容占比越高,优先级越高
  return a.length - b.length;
});

console.log(sortedArr); // 输出: ['another', 'another world', 'foo-another-bar']

逻辑说明

  1. 完全匹配优先:如果字符串和正则的匹配源完全一致(比如"another"和/another/),直接排在最前;
  2. 匹配位置权重:匹配子串在字符串中出现的位置越靠前,排序越优先;
  3. 内容占比权重:当匹配位置相同时,字符串长度越短,说明匹配内容的占比越高,优先级更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 22:25:17