Home > database >  regex for matching all characters in the string any where
regex for matching all characters in the string any where

Time:12-29

I need a regex for matching all characters in the string. But it is not matter where that characters.

EG - Input array - [a, b, c] Following words should match

abc
axbxc
cybxbxca

But should not match following. Because these words has not all input charters.

axbxyz
bxba

CodePudding user response:

You can use Array.prototype.every() with String.prototype.includes() to filter the matching words:

const inputArray = ['a', 'b', 'c'];

const words = [
  // PASS:
  'abc',
  'axbxc',
  'cybxbxca',

  // FAIL:
  'axbxyz',
  'bxba',
];

const result = words.filter(word => inputArray.every(str => word.includes(str)));
console.log(result); // ["abc", "axbxc", "cybxbxca"]

CodePudding user response:

You need a regexp like ^(?=.*a)(?=.*b)..., which you can build dynamically from the input:

const inputArray = ['a', 'b', 'c'];

let re = RegExp('^'   inputArray.map(x => '(?=.*'   x   ')').join(''))

const words = [
    'abc',
    'axbxc',
    'cybxbxca',
    'axbxyz',
    'bxba',
];

console.log(words.map(w => [w, re.test(w)]))

If the input can contain regex special symbols, don't forget to escape them properly.

  • Related