【发布时间】:2021-09-02 04:29:12
【问题描述】:
当我在在线检查器https://regex101.com 中单独测试它们时,我遇到了 regex.match 与匹配的文件名不匹配的问题@
谁能在下面的代码中发现问题?
问:我应该使用 regex.test 代替 match 吗?如果是,当它包含变量时如何创建正则表达式?
它应该匹配以以下开头的所有文件:ES_(Stay) True - Lars Eriksson
文件和目录列表在 fs.readdirSync 找到的路径中:
.DS_Store
ES_(Stay) True - Lars Eriksson (22).mp3
ES_(Stay) True - Lars Eriksson (22).mp3.crdownload
ES_(Stay) True - Lars Eriksson.mp3
ES_(Stay) True - Lars Eriksson.mp3.crdownload
Other - File (22).mp3
Other - File (22).mp3.crdownload
Other - File.crdownload
Other - File.mp3
originals
正则表达式转换为:
/^(ES_\(Stay\) True - Lars Eriksson(?: \([0-9]+\))?.mp3(?:.crdownload?)?)$/
木偶脚本:
const puppeteer = require('puppeteer');
const fs = require('fs');
(async () => {
function escapeRegex(string) {
return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
let path = '/path/to/files/';
let title = 'ES_(Stay) True';
let artist = 'Lars Eriksson';
title = escapeRegex(title);
artist = escapeRegex(artist);
let regex = `/^(${title} - ${artist}(?: \\([0-9]+\\))?\.mp3(?:\.crdownload?)?)$/`;
console.log(regex);
fs.readdirSync(path)
.filter(f => {
regex.match();
})
.map(f => {
console.log(f);
});
})();
【问题讨论】:
标签: javascript node.js regex puppeteer