Martin AJ
Martin AJ

Reputation: 6697

How can I count the length of string in RegEx?

Here is my pattern:

^(?=.*[a-z])(?=.*[A-Z]).+$

It's a password validation. As you know:

^ Matches the start of the string

(?=.*[a-z]) checks if somewhere in the string is a lowercase character

(?=.*[A-Z]) checks if somewhere in the string is a uppercase character


Now I need to add some count conditions to the pattern. I mean, I need to count:

  1. The length of whole string should be more than 6 characters. (I guess I should use something like this {6,}, but I don't know how should I use it)
  2. The number of capital characters should be at least three ones. (this condition isn't very important, if implementing that is hard, I can ignore it)

How can I do that?

Upvotes: 0

Views: 66

Answers (2)

Nadjib Khelifati
Nadjib Khelifati

Reputation: 559

Try this:

^(?=.*[a-z])(?=(.*[A-Z]){3,}).{6,}$

You can check here

Upvotes: -1

Sebastian Proske
Sebastian Proske

Reputation: 8413

Quantifiers are key here. You can use {6,} for your matching pattern for the first conditions and expand your second lookahead a bit for your second condition, like

^(?=.*[a-z])(?=(?:[^A-Z]*[A-Z]){3}).{6,}$

See https://regex101.com/r/DjSqbr/1

Note: I have extended [^A-Z] to [^A-Z\r\n] to work properly with multline strings.

Upvotes: 2

Related Questions