【发布时间】:2016-11-27 20:36:02
【问题描述】:
假设我有一个文件数组,这些文件已从更大的文件数组中与下面代码中的表达式进行匹配。为简单起见,我会说文件数组如下:
prefix_pt1_pt3_pt5_pt6
prefix_pt1_pt4_pt5_pt6
prefix_pt1_pt3_pt4_pt6
prefix_pt1_pt5_pt6
但是文件名不一定是连续的。
我想优先考虑每个捕获组。到目前为止,我提出的代码只会对文件进行优先级排序,直到它与捕获组不匹配,因此从上面的文件中它将只选择第一个。我希望 prefix_pt1_pt3_pt4_pt6 成为我函数的结果。
const parts = ['p1', 'p2', 'p3', 'p4', 'p5', 'p6'];
const existsRegex = new RegExp(
regexEscape(params.folder) +
regexEscape(prefix) +
parts.reduce((result, part) => result + `(_${regexEscape(part)})?`, '')
);
const validFiles = scanPath(existsRegex);
if (validFiles.length) {
const chosenFile = validFiles.reduce((file, currentFile) => {
const matches = currentFile.match(existsRegex);
const killFrom = matches.indexOf(undefined);
if (killFrom > 0) matches.length = killFrom;
if (matches.length > file.length) return matches;
return file;
}, []);
}
【问题讨论】:
标签: javascript arrays regex sorting filtering