Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
690 views
in Technique[技术] by (71.8m points)

java - Regex to match at least 2 digits, 2 letters in any order in a string

I'm trying to create a regex to pattern match (for passwords) where the string must be between 8 and 30 characters, must have at least 2 digits, at least 2 letters (case-insensitive),at least 1 special character, and no spaces.

I've got the spaces and special character matching working, but am getting thrown on the 2 digits and 2 letters because they don't need to be consecutive.

i.e. it should match a1b2c$ or ab12$ or 1aab2c$.

Something like this for the letters?

(?=.*[a-zA-Z].*[a-zA-Z])  // Not sure.

This string below works, but only if the 2 letters are consecutive and the 2 numbers are consecutive..it fails if the letters, numbers, special chars are interwoven.

(?=^.{8,30}$)((?=.*\d)(?=.*[A-Za-z]{2})(?=.*[0-9]{2})(?=.*[!@#$%^&*?]{1})(?!.*[\s]))^.* 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you don't want letters to have to be consecutive (?=.*[a-zA-Z].*[a-zA-Z]) is correct approach. Same goes to digits (?=.*\d.*\d) or (?=(.*\d){2}).

Try this regex

(?=^.{8,30}$)(?=(.*\d){2})(?=(.*[A-Za-z]){2})(?=.*[!@#$%^&*?])(?!.*[\s])^.*

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...