Angelo
Angelo

Reputation: 136

Regex [4 characters, one letter, Cannot be all the same character]

Requirements: Must be more than 4 characters Must contain at least one letter a-zA-Z Cannot be all the same character (regardless of length)

based on a previous answer I came up with:

(?!.*([A-Za-z0-9])\1{2})(?=.*[a-z]).{5,}

and it works fine not matching values like "aaaaa".

(?!.*([A-Za-z0-9])\1{2}) makes sure that none of the chars repeat more than twice in a row.

(?=.*[a-z]) requires at least one lowercase letter

The problem is I need the "row" to be valid (I use the regex for validation purposes) if the word with repeated characters is part of a sentence (not on his own) e.g. "includes AAA batteries".

Upvotes: 0

Views: 560

Answers (2)

gil.fernandes
gil.fernandes

Reputation: 14621

You could try to remove the ".*" expression from the first negative look-ahead:

(?!([A-Za-z0-9])\1{2})(?=.*[a-z]).{5,}

This now matches: hello AAAAA test or includes AAA batteries

But it still does not match: AAAAA

Edit:

If you want to support also expressions like AAAAA batteries, you should actually use:

(?!([A-Za-z0-9])\1{2}$)(?=.*[a-z]).{5,}

Credits go to @Brian Stephens on this correction.

Upvotes: 1

Faan Veldhuijsen
Faan Veldhuijsen

Reputation: 106

I think this regex is what you need:

(?=.*[a-zA-Z])(?=.*\d)(?!.*([A-Za-z0-9])\1{1}).{4,}

To explain it a bit:

(?=.*[a-zA-Z])             // To make sure there is at least one letter (uppercase or lower case)
(?!.*([A-Za-z0-9])\1{2})   // To make sure nothing will repeat twice in a row
.{4,}                      // Have at least 4 characters

This regex will allow things like

aa23
A123
a1234
A1234
$%$%a
$%$%A

To exclude 'weird' characters you'll need to add (?!.*[\W]) like so:

(?=.*[a-zA-Z])(?!.*[\W])(?!.*([A-Za-z0-9])\1{1}).{4,}

Upvotes: 1

Related Questions