YaW
YaW

Reputation: 12142

RegEx - Require minimum length of one group

I'm trying to make a nickname validator. Here are the rules I want:

  • Total character count must be between 3 and 15
  • There can be two non-consecutive spaces
  • Only letters (a-z) are allowed
  • Each word separated by a space can begin with an uppercase letter, the rest of the word must be lowercase
  • At least one of the words must have 3 or more characters

This is what I currently have which checks the four first rules, but I have no idea how to check the last rule.

^(?=.{3,15}$)(\b[A-Z]?[a-z]* ?\b){1,3}$

Should match:

Shouldn't match:

Upvotes: 2

Views: 2053

Answers (2)

bobble bubble
bobble bubble

Reputation: 18490

but I have no idea how to check the last rule

As you only allow [A-Za-z] and space in your regex, you could simply use (?=.*?\S{3}) which looks ahead for 3 non white-space characters. .*? matches lazily any amount of any characters.

As soon as 3 non white-space characters are required the initial lookahead can be improved to the negative ^(?!.{16}) as the minimum of 3 is already required in \S{3}[A-Za-z][a-z]*

Further you can drop the initial \b which is redundant as there can only be start or space before.

^(?!.{16})(?=.*?\S{3})(?:[A-Za-z][a-z]* ?\b){1,3}$

Here is a demo at regex101 (for more regex info see the SO regex faq)

If your tool supports atomic groups, improve performance by use of (?> instead of (?:

Upvotes: 0

Matt.G
Matt.G

Reputation: 3609

Try Regex: ^(?=[A-Za-z ]{3,15}$)(?=[A-Za-z ]*[A-Za-z]{3})(?:\b[A-Z]?[a-z]*\ ?\b){1,3}$

Demo

For the last rule, a positive lookahead without space was used (?=[A-Za-z ]*[A-Za-z]{3})

Upvotes: 2

Related Questions