4

I am looking for a regex to match words formed with specific characters without repeating any character: Example, for a b c and d, how to specify a regex to match those strings:

bdca (match) adb (match) abcg (fail) aab (fail) I tried with ^[abcd]{1,4}$ but it accepts repeated characters (last example).

Please any help?

iouhammi
  • 1,108
  • 15
  • 29

1 Answers1

10

You can use this regex based on negative lookahead:

^(?:([abcd])(?!.*\1)){1,4}$

RegEx Demo

Breakup:

^            Line start
(?:          Start non-capturing group
  ([abcd])   Match a or b or c or d and group it 
  (?!.*\1)   Negative lookahead to fail the match if same grouped char is ahead
){1,4}       1 to 4 occurrences of non-capturing group
$            Line end
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/96816/discussion-between-anubhava-and-iouhammi). – anubhava Dec 02 '15 at 16:29