简体   繁体   中英

Javascript - Regular Expression For two uppercase, lowercase and numbers

I am new to regular expression.

I have written one for uppercase, lowercase, 10 characters (min) and a number.

/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])\S{10,}$/g

This validates correctly.

I was wondering if I could run a check for a minimum of two uppercase chars, two lowercase chars and two numbers?

I have tried:

/^(?=.*[A-Z]{2,})(?=.*[a-z]{2,})(?=.*[0-9]{2,})\S{10,}$/g

Cheers

Yes, it's easy, you only need to repeat twice the whole content of each lookahead (using a non-capturing group) :

/^(?=(?:.*[A-Z]){2})(?=(?:.*[a-z]){2})(?=(?:.*[0-9]){2})\S{10,}$/

You can improve the pattern using negated character classes:

/^(?=(?:[^A-Z]*[A-Z]){2})(?=(?:[^a-z]*[a-z]){2})(?=(?:[^0-9]*[0-9]){2})\S{10,}$/

Note: since you test all the string with a single pattern anchored at the begining and at the end, you don't need to add "g" for a global research.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM