Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match exactly one of each from set of characters

Tags:

regex

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.

like image 844
SDekov Avatar asked Mar 14 '16 14:03

SDekov


1 Answers

I would think of capturing and using a lookahead to check if the same character is not ahead.

\b(?:([abcd])(?!\w*?\1)){4}\b
  • (?: opens a non capture group for repetition
  • \b matches a word boundary
  • ([abcd]) captures one of [abcd]
  • (?!\w*?\1) checks if the captured character is not ahead with any amount of \w in between
  • {4}\b 4 times until another word boundary

See demo at regex101   (works only, if a lookahead is available in your regex flavor)

like image 171
bobble bubble Avatar answered Sep 22 '22 19:09

bobble bubble