effe
effe

Reputation: 1365

regex to match entire words containing mandatory and allowed characters

I want to match entire words that containing mandatory chars and allowed chars.

For example
Mandatory chars are : [ c , a , t ]
Allowed chars are : [ y , s]

cat   : passed (all mandatories are here)
caty  : passed (all mandatories here and only allowed "y" char)
casy  : failed (mandatory 't' is absent)
catso : failed (all mandatories but an intruder "o")

What is the appropriate REGEX code for this?

Upvotes: 0

Views: 2471

Answers (2)

Desolator
Desolator

Reputation: 22779

try this one and tell me if it needs any enhancements:

/^ca[t]+[ys]*$/i

Upvotes: 1

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89639

you can do that with this kind of pattern, if your regex flavor have the lookahead feature:

 \b(?=[a-z]*?c)(?=[a-z]*?a)(?=[a-z]*?t)[actys]+\b

Note that lookarounds can be expensive due to the backtracks. You can limit it using two tricks:

1) using more constraints for character classes:

\b(?=[a-bd-z]*c)(?=[b-z]*a)(?=[a-su-z]*t)[actys]+\b

2) using possessive quantifiers (if supported)

\b(?=[a-bd-z]*+c)(?=[b-z]*+a)(?=[a-su-z]*+t)[actys]++\b

or atomic groups in place of:

\b(?=(?>[a-bd-z]*)c)(?=(?>[b-z]*)a)(?=(?>[a-su-z]*)t)(?>[actys]+)\b

Upvotes: 4

Related Questions