I'm having issues with regex.match not matching filenames which do match when I test them individually in an online checker https://regex101.com
Can anyone spot the problem in code below?
Q: Should I be using regex.test instead of match? If yes, how do I create the regex when it contains variables?
It should match all files starting with: ES_(Stay) True - Lars Eriksson
List of files and directory in path found by 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
The regex converts to:
/^(ES_\(Stay\) True - Lars Eriksson(?: \([0-9]+\))?.mp3(?:.crdownload?)?)$/
Puppeteer script:
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);
});
})();