minimatch failed to match the string and regexp

98 views Asked by At

I wanted to construct a regexp that won't match any elements in a given array(each element is a string). For example, if the given array is ['a','b'], then the regexp will match any string except for 'a' and 'b'. So I wrote a function like this:

const generateRegex = array => {
  const escapedStrings = array.map(s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
  const regex = `^(?!.*(?:${escapedStrings.join('|')})).*$`
  return regex
}

And it worked well. For example:

const generateRegex = array => {
  const escapedStrings = array.map(s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
  const regex = `^(?!.*(?:${escapedStrings.join('|')})).*$`
  return regex
}
const regExp = generateRegex(['a','b'])
console.log(new RegExp(regExp).test('a'))   // false
console.log(new RegExp(regExp).test('b'))   // false
console.log(new RegExp(regExp).test('c'))   // true

For some reason, I had to use minimatch to do things what new RegExp().test() does. So I wrote the code like this:

const minimatch = require("minimatch");
const generateRegex = array => {
  const escapedStrings = array.map(s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
  const regex = `^(?!.*(?:${escapedStrings.join('|')})).*$`
  return regex
}
const regExp = generateRegex(['a','b'])
console.log(minimatch('a',regExp))   // false
console.log(minimatch('b',regExp))   // false
console.log(minimatch('c',regExp))   // false

As you can see, all the logs were false. This was strange since the string c exactly matched the regExp.

0

There are 0 answers