如何用正则表达式过滤数组并按匹配度从高到低排序?
按正则匹配度对过滤后的数组排序
现有数组:
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']
逻辑说明
- 完全匹配优先:如果字符串和正则的匹配源完全一致(比如
"another"和/another/),直接排在最前; - 匹配位置权重:匹配子串在字符串中出现的位置越靠前,排序越优先;
- 内容占比权重:当匹配位置相同时,字符串长度越短,说明匹配内容的占比越高,优先级更高。
内容的提问来源于stack exchange,提问作者Bijan Regmi
相关产品推荐
相关产品推荐

