使用 Puppeteer 过滤 regex.match 目录中的文件

Filtering files in directory with regex.match using Puppeteer

我遇到了 regex.match 不匹配文件名的问题,当我在在线检查器中单独测试它们时确实匹配 https://regex101.com

谁能找出下面代码中的问题?

问:我应该使用 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);
    });

})();

我认为要将字符串转换为正则表达式,您应该使用 RegExp() 而不仅仅是将其用作字符串

let regex = new RegExp(`^(${title} - ${artist}(?: \([0-9]+\))?\.mp3(?:\.crdownload?)?)$`, 'gi');
console.log(regex);
  • 你也习惯了regex.match()当没有任何东西可以匹配时你期望匹配什么你试图匹配正则表达式而不是它应该是什么
f.match(regex)

你的代码应该是这样的

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 = new RegExp(`^(${title} - ${artist}(?: \([0-9]+\))?\.mp3(?:\.crdownload?)?)$`, 'gi');
console.log(regex);

let file = fs.readdirSync(path),
matched = file.filter(f => f.match(regex))
console.log(matched)
})();

结果

0: "ES_(Stay) True - Lars Eriksson (22).mp3"
1: "ES_(Stay) True - Lars Eriksson (22).mp3.crdownload"
2: "ES_(Stay) True - Lars Eriksson.mp3"
3: "ES_(Stay) True - Lars Eriksson.mp3.crdownload"