1

I have to write regex that checks if string:

  • length is 5-15 characters long
  • has at least 2 uppercase letters
  • has at least 2 lowercase letters
  • and has 1 digit

I appreciate any help because I am really stuck on this and don't have any ideas how to solve this.

0

3 Answers 3

6

You can use look ahead to check all conditions, and then match 5 to 15 characters (any), making sure there is nothing else (^ and $):

^(?=(?:.*[A-Z]){2})(?=(?:.*[a-z]){2})(?=.*\d).{5,15}$

  • ^: start of string
  • (?= ): positive look ahead. Does not grab any characters, but just looks ahead to see if the pattern would be matched
  • (?: ): make this group non-capturing, i.e. you'll not get it as capturing group that you can reference with $1 or \1 (language dependent)
  • .*[A-Z]: 0 or more character(s) followed by a capital letter
  • .*[a-z]: 0 or more character(s) followed by a lower case letter
  • .*\d: 0 or more character(s) followed by a digit
  • {2}: previous pattern must match twice
  • .{5-15}: 5 to 15 characters.
  • $: end of string

In JavaScript you can test a string against a regular expression with test, for example:

var regex = /^(?=(?:.*[A-Z]){2})(?=(?:.*[a-z]){2})(?=.*\d).{5,15}$/;

console.log(regex.test('a9B1c')); // false, missing capital letter
console.log(regex.test('a9B1cD')); // true

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I recently started to use regex and never heard or used look ahead.
0

trinctot was right first, but depending on who is using your code and for what, this might be easier to maintain/modify:

var lowerPass = 2 <= (string.match(/[a-z]/g) || []).length;
var upperPass = 2 <= (string.match(/[A-Z]/g) || []).length;
var digitPass = 1 <= (string.match(/[0-9]/g) || []).length;
var lengthPass = 5 <= string.length <= 15;

var stringPass = lowerPass + upperPass + digitPass + lengthPass == 4;

Comments

0

Try this

    ^([a-z]{2,}[A-Z]{2, }[0-9]{1}+) {5, 15}$

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.