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); }); })();
Advertisement
Answer
I think to convert string to regex you should use RegExp()
not just use it as string for example
let regex = new RegExp(`^(${title} - ${artist}(?: \([0-9]+\))?.mp3(?:.crdownload?)?)$`, 'gi'); console.log(regex);
- also you are used
regex.match()
what do you expect to match when there’s nothing to match you are trying to match the regex with nothing it’s should to be
f.match(regex)
your code should to be like that
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) })();
Result
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"