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
220 views
in Technique[技术] by (71.8m points)

java - String contains at least one digit

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?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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

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;
    }

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

2.1m questions

2.1m answers

60 comments

56.9k users

...