Home > Software engineering >  Regex to get length of group of character classes
Regex to get length of group of character classes

Time:02-13

I have a workaround for this, but was hoping to find a purely regex solution.

The requirements are:

  • has one required character
  • only pulls from a pool of approved characters
  • minimum length of 4
  • single word, no whitespace

e.g.
required character: m
pool of characters: [a,b,e,l]

Possible matches:
mabel
abemal
labeam

won't match:
a mael
ama
label

So far I have this expression, but putting a {4,} after it thinks I'm talking about multiplying word matches by 4.
^\b(?:[abel]*[m] [abel]*)\b

CodePudding user response:

You can use

^(?=.*[m])[abelm]{4,}$

^ start of a line or string

Positive Lookahead (?=.*[m])
Asserts that the string contains at least 1 m character

[abelm]{4,} matches characters in the list abelm
between 4 and unlimited times, as many times as possible.
(greedy) (case sensitive)

$ end of a line or string

  • Related