Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for words formed with specific characters

Tags:

regex

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?

like image 537
iouhammi Avatar asked Dec 25 '22 11:12

iouhammi


1 Answers

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
like image 95
anubhava Avatar answered Jan 09 '23 18:01

anubhava