[英]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.我正在尝试创建一个正则表达式来模式匹配(用于密码),其中字符串必须在 8 到 30 个字符之间,必须至少有 2 个数字,至少 2 个字母(不区分大小写),至少 1 个特殊字符,以及没有空间。
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.我有空格和特殊字符匹配工作,但我被抛出 2 位数字和 2 个字母,因为它们不需要连续。
ie it should match a1b2c$
or ab12$
or 1aab2c$
.即它应该匹配a1b2c$
或ab12$
或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.下面的字符串有效,但仅当 2 个字母连续且 2 个数字连续时才有效。如果字母、数字、特殊字符交织在一起,则失败。
(?=^.{8,30}$)((?=.*\\d)(?=.*[A-Za-z]{2})(?=.*[0-9]{2})(?=.*[!@#$%^&*?]{1})(?!.*[\\s]))^.*
If you don't want letters to have to be consecutive (?=.*[a-zA-Z].*[a-zA-Z])
is correct approach.如果您不希望字母必须是连续的(?=.*[a-zA-Z].*[a-zA-Z])
是正确的方法。 Same goes to digits (?=.*\\\\d.*\\\\d)
or (?=(.*\\\\d){2})
.同样适用于数字(?=.*\\\\d.*\\\\d)
或(?=(.*\\\\d){2})
。
Try this regex试试这个正则表达式
(?=^.{8,30}$)(?=(.*\\d){2})(?=(.*[A-Za-z]){2})(?=.*[!@#$%^&*?])(?!.*[\\s])^.*
Your guess would be pretty accurate.你的猜测会很准确。 It can be made to look a little more elegant with parens.使用括号可以使它看起来更优雅一些。
(?=(.*[a-zA-Z]){2})
Sounds like you are on the right track though.听起来你是在正确的轨道上。
Use a loop to traverse the string:使用循环遍历字符串:
/**
* Checks to see if the specified string has between 8 and 30 characters, has at least 2 digits, at least 2 letters, at least one special character, and no spaces.
* @param s the String to be checked
* @return s, if it passes the above test
* @throws IllegalArgumentException if it does not
*/
public static String check(String s)
{
IllegalArgumentException invalid = new IllegalArgumentException();
if(s.length() < 8 || s.length() > 30)
throw invalid;
int letters = 0, numbers = 0, specialChars = 0;
for(char c : s.toCharArray())
{
if(c == ' ')
throw invalid;
else if(Character.isLetter(c))
++letters;
else if(Character.isDigit(c))
++numbers;
else
++specialChars;
}
if(letters < 2 || numbers < 2 || specialChars < 1)
throw invalid;
return s;
}
i observe your examples that you provide are not 8 to 30 characters我观察到您提供的示例不是 8 到 30 个字符
try this pattern once if you want 8-30 characters如果您想要 8-30 个字符,请尝试此模式一次
(?=[^\s]*[^\sa-zA-Z0-9][^\s]*)(?=[^\s]*[a-zA-Z][^\s]*[A-Za-z][^\s]*)(?=[^\s]*\d[^\s]*\d[^\s]*)[^\s]{8,30}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.