A regular expression to determine if a string contains 1-4 specific characters

Not sure if this is the best way to express this, so I’ll just give an example. Say I have characters a,b,c,d. I want to accept any string that has 0 or 1 of each character in any order. Lines such as "ab" "abcd" "dcab"would be acceptable. Is it possible to do this only with regular expressions?

The only thing I came up with is this ((a|b|c|d){0,1}){0,4}. However, this would not work, since it would accept strings such as "aaaa".

+4
source share
3 answers

The question seems very easy. But this is really not the case. Here you go

^([abcd])(?:(?!\1)([abcd]))?(?:(?!\1|\2)([abcd]))?(?:(?!\1|\2|\3)([abcd]))?$

Demo

Reduced,

^([abcd])((?!\1)[abcd])?((?!\1|\2)[abcd])?((?!\1|\2|\3)[abcd])?$

Demo

Sample Explanation:

  • ^ It is claimed that we are at the beginning.
  • ([abcd]) (a b c d). .
  • (?!\1)[abcd] , . ((?!\1)[abcd])?, . , .
  • ((?!\1|\2)[abcd])? char, . , .
  • ((?!\1|\2|\3)[abcd])? char, . , .
  • $ , .

^(?:(?!(.).*\1)[abcd])+$

:

  • (?!(.).*\1) , .
  • (?:(?!(.).*\1)[abcd])+ (a b c d), . , ( 1 4).

DEMO

PCRE (*SKIP)(*F),

^.*(.).*\1.*$(*SKIP)(*F)|^[abcd]+$

:

  • ^.*(.).*\1.*$ .
  • (*SKIP)(*F) . , , . , | , .
  • ^ , .
  • [abcd]+ . , aba bba ..

  • $ , .

DEMO

+4

, , . :

^(?>([abcd])(?!.*\1))+$

[abcd] lookahead, . + . , (?> (?:, , .

regex101;

+2

Johnny 5 +1
here is my pattern

^(?!.*(.).*\1)([abcd]+)$  

Demo

+2
source

All Articles