Match exactly one of each from set of characters

Viewed 2307

I am trying to match a specific set of characters but 1 and only 1 of each.

For example if the set is [abcd], I want to match string containing these exact characters in any order.

abcd  - true
bcad  - true
abc   - false (need all characters)
abbd  - false
abcdd - false

From what I understand so far there is no easy way to achieve this with RegEx but no answer was conclusive enough.

5 Answers

See bobble bubble's excellent answer for a real regex solution (which is sometimes necessary). This answer uses sorting and string equality instead of a single regex:

var set = 'bcad'; // in any order
var tests = [
  'abcd',  // true
  'bcad',  // true
  'abc',   // false (need all characters)
  'abbd',  // false
  'abcdd', // false
];

var setSorted = set.split('').sort().join();

for (var i = 0; i < tests.length; i++) {
  var pass = setSorted == tests[i].split('').sort().join();
  console.log(`${tests[i]}: ${pass}`);
}

Related