简体   繁体   English

Java String.matches()正则表达式

[英]Java String.matches() regular expressions

I am trying to use the matches() function to check a user-entered password for certain conditions 我正在尝试使用matches()函数检查某些情况下用户输入的密码

"Contains six alphanumeric characters, at least one letter and one number" “包含六个字母数字字符,至少一个字母和一个数字”

Here is my current condition for checking for alphanumeric characters 这是我目前检查字母数字字符的条件

pword.matches("([[a-zA-Z]&&0-9])*")

unfortunately in example using "rrrrZZ1" as the password this condition still returns false 不幸的是,在使用“ rrrrZZ1”作为密码的示例中,此条件仍然返回false

What would be the correct regular expression? 正确的正则表达式是什么? Thank you 谢谢

Someone else here may prove me wrong, but this is going to be very difficult to do without an excessively complex regular expression. 这里的其他人可能证明我错了,但是如果没有一个过于复杂的正则表达式,这将很难做到。 I'd just use a non-regular expression approach instead. 我将只使用非正则表达式方法。 Set 3 booleans for each of your conditions, loop through the characters and set each boolean as each condition is met, and if all 3 booleans don't equal true, then fail the verification. 为每个条件设置3个布尔值,遍历字符并在满足每个条件时设置每个布尔值,如果所有3个布尔值都不等于true,则验证失败。

You could use something as simple as this: 您可以使用以下简单的方法:

public boolean validatePassword(String password){
    if(password.length() < 6){
        return false;
    }
    boolean foundLetter = false;
    boolean foundNumber = false;
    for(int i=0; i < password.length(); i++){
        char c = password.charAt(i);
        if(Character.isLetter(c)){
            foundLetter = true;
        }else if(Character.isDigit(c)){
            foundNumber = true;
        }else{
            // Isn't alpha-numeric.
            return false;
        }
    }
    return foundLetter && foundNumber;
}

I agree with ziesemer - use a validatePassword() method instead of cramming it into regex. 我同意ziesemer-使用validatePassword()方法而不是将其塞入正则表达式中。

Much more readable for a developer to maintain. 对于开发人员而言,更具可读性。

If you do want to go down the regex path, it is achievable using zero width positive lookaheads. 如果您确实想沿着正则表达式路径前进,则可以使用零宽度正向超前行来实现。

Contains six characters, at least one letter and one number: 包含六个字符,至少一个字母和一个数字:

^.*(?=.{6,})(?=.*[a-zA-Z]).*$

I changed your six alphanumeric characters to just characters . 我将您的六个alphanumeric characters更改为仅characters Supports more complex passwords :) 支持更复杂的密码:)

Great post on the topic: 关于该主题的好文章:

http://www.zorched.net/2009/05/08/password-strength-validation-with-regular-expressions/ http://www.zorched.net/2009/05/08/password-strength-validation-with-regular-expressions/

Bookmark this one too: 也将此书签添加为书签:

http://www.regular-expressions.info/ http://www.regular-expressions.info/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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