java 字符串至少包含一位

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6419262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 15:48:48  来源:igfitidea点击:

String contains at least one digit

javaregex

提问by idipous

I am trying to see whether a string contains at least a digit or a lowercase or an uppercase.

我试图查看一个字符串是否至少包含一个数字、一个小写字母或一个大写字母。

I have written something like this:

我写过这样的东西:

      int combinations = 0;
      string pass = "!!!AAabas1";

      if (pass.matches("[0-9]")) {
          combinations = combinations + 10;
      }

      if (pass.matches("[a-z]")) {
          combinations =combinations + 26;
      }

      if (pass.matches("[A-Z]")) {
          combinations =combinations + 26;
      }

However I don't understand why I cannot get combinations to go to 36. They just remain at 0. What am I doing wrong?

但是我不明白为什么我不能让组合达到 36。它们只是保持在 0。我做错了什么?

回答by Hrzio

You could use Pattern instead, I think "matches" method looks for the whole string to match the regular expression.

您可以改用 Pattern,我认为“matches”方法会查找整个字符串以匹配正则表达式。

Try the next code:

尝试下一个代码:

    int combinations = 0;
    String pass = "!!AAabas1";
    if (Pattern.compile("[0-9]").matcher(pass).find()) {
        combinations = combinations + 10;
    }

    if (Pattern.compile("[a-z]").matcher(pass).find()) {
        combinations = combinations + 26;
    }

    if (Pattern.compile("[A-Z]").matcher(pass).find()) {
        combinations = combinations + 26;
    }

回答by hoipolloi

Here's my attempt. Note, this uses unicode categories for validation so is non-latin language friendly.

这是我的尝试。请注意,这使用 unicode 类别进行验证,因此对非拉丁语言友好。

import java.util.regex.Pattern;

public class PasswordValidator {

    public static void main(String[] args) {
        final PasswordValidator passwordValidator = new PasswordValidator();
        for (String password : new String[] { "abc", "abc123", "ABC123", "abc123ABC", "!!!AAabas1", "гшщз",
                "гшщзЧСМИ22" }) {
            System.out.printf("Password '%s' is %s%n", password, passwordValidator.isValidPassword(password) ? "ok"
                    : "INVALID");
        }
    }
    private static final Pattern LOWER_CASE = Pattern.compile("\p{Lu}");
    private static final Pattern UPPER_CASE = Pattern.compile("\p{Ll}");
    private static final Pattern DECIMAL_DIGIT = Pattern.compile("\p{Nd}");

    /**
     * Determine if a password is valid.
     * 
     * <p>
     * A password is considered valid if it contains:
     * <ul>
     * <li>At least one lower-case letter</li>
     * <li>At least one upper-case letter</li>
     * <li>At least one digit</li>
     * </p>
     * 
     * @param password
     *            password to validate
     * @return True if the password is considered valid, otherwise false
     */
    public boolean isValidPassword(final String password) {
        return containsDigit(password) && containsLowerCase(password) && containsUpperCase(password);
    }

    private boolean containsDigit(final String str) {
        return DECIMAL_DIGIT.matcher(str).find();
    }

    private boolean containsUpperCase(final String str) {
        return UPPER_CASE.matcher(str).find();
    }

    private boolean containsLowerCase(final String str) {
        return LOWER_CASE.matcher(str).find();
    }

}

Here's the output:

这是输出:

Password 'abc' is INVALID
Password 'abc123' is INVALID
Password 'ABC123' is INVALID
Password 'abc123ABC' is ok
Password '!!!AAabas1' is ok
Password 'гшщз' is INVALID
Password 'гшщзЧСМИ22' is ok

回答by joeslice

The problem is that matchestries to match the entire input string.

问题是matches试图匹配整个输入字符串。

Instead, try creating a Pattern, then from there create a Matcher, and then use the findmethod.

相反,尝试创建一个Pattern,然后从那里创建一个Matcher,然后使用find方法。

The Pattern javadocshould help a great deal.

模式的javadoc应该帮助很大。

回答by ColinD

While using a regex for this can obviously work, Guava's CharMatcherclass might be a bit more appropriate to what you're trying to do:

虽然为此使用正则表达式显然可以工作,但GuavaCharMatcher类可能更适合您要执行的操作:

if (CharMatcher.inRange('0', '9').matchesAnyOf(pass))
  combinations += 10;
if (CharMatcher.inRange('a', 'z').matchesAnyOf(pass))
  combinations += 26;
if (CharMatcher.inRange('A', 'Z').matchesAnyOf(pass))
  combinations += 26;

回答by CooL AndroDev

String str_rno = "CooL8";

boolean Flag = false;

String[] parts = str_rno.split(""); 

for (int i = 0; i < str_rno.length(); i++) {

    String part1 = parts[i + 1];      

    if (Character.isDigit(str_rno.charAt(i))) {
        System.out.println(" " + i + " " + part1 + " digit");
        Flag = true;
    } else {
        System.out.println(" " + i + " " + part1 + " char ");
    }

}


if(Flag==true){
    Toast.makeText(getApplicationContext(),"String contain 1 digit",Toast.LENGTH_SHORT).show();
}

if(Flag==flase){
    Toast.makeText(getApplicationContext(),"String not contain 1 digit",Toast.LENGTH_SHORT).show();
}