正则表达式匹配字符串中任意顺序的至少2位数字,2个字母
我正在尝试创建一个模式匹配的正则表达式(用于密码),其中字符串必须在8到30个字符之间,必须至少有2个数字,至少2个字母(不区分大小写),至少1个特殊字符,以及空间不足。
我有空格和特殊字符匹配工作,但我被抛出2位数字和2个字母,因为它们不需要连续。
即它应匹配a1b2c$
或ab12$
或1aab2c$
。
这些字母有这样的东西吗?
(?=.*[a-zA-Z].*[a-zA-Z]) // Not sure.
下面这个字符串有效,但只有当2个字母是连续的并且2个数字是连续的时…如果字母,数字,特殊字符交织在一起则失败。
(?=^.{8,30}$)((?=.*\\d)(?=.*[A-Za-z]{2})(?=.*[0-9]{2})(?=.*[!@#$%^&*?]{1})(?!.*[\\s]))^.*
如果你不希望字母必须是连续的(?=.*[a-zA-Z].*[a-zA-Z])
是正确的方法。 数字相同(?=.*\\d.*\\d)
或(?=(.*\\d){2})
。
试试这个正则表达式
(?=^.{8,30}$)(?=(.*\\d){2})(?=(.*[A-Za-z]){2})(?=.*[!@#$%^&*?])(?!.*[\\s])^.*
使用循环遍历字符串:
/** * 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; }
你的猜测非常准确。 它可以使用parens看起来更优雅。
(?=(.*[a-zA-Z]){2})
听起来你是在正确的轨道上。
我注意到你提供的例子不是8到30个字符
如果你想要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}