-2

I'm trying to create a regex code to match the following criteria but have thus far been unable.

  • At least two upper-case letters
  • At least two lower-case letters
  • At least one number.

Here is my code: At the moment I have used these 2 expressions to check for length

  if (String.valueOf(string1).length() <= 8){j =0;}      
  if (!string1.matches("[A-Za-z0-9]*")){j =0;}

.int j is a variable im using to check if the conditions are met!

bert
  • 17
  • 1
  • 3
    Have you tried anything yet? Which sites are you using for regular expression references? – VGR Oct 21 '16 at 20:23
  • ^ Please add that into your question before it is downvoted further. – halfer Oct 21 '16 at 20:25
  • ^ Please add that into your question `using code formatting` before it is downvoted further. – halfer Oct 21 '16 at 20:26
  • What is `j` and what is the value `0` supposed to mean? – UnholySheep Oct 21 '16 at 20:26
  • I have recently used the following to do password validation. http://www.passay.org – Alan Hay Oct 21 '16 at 20:31
  • 2
    [Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.](https://en.wikiquote.org/wiki/Jamie_Zawinski) -- Jamie Zawinski – Andreas Oct 21 '16 at 20:38

1 Answers1

0

Well I see a non-regex way to go about it:

public boolean isValidPassword(String s) {
    int lowerCase = 0;
    int upperCase = 0;
    int numeric = 0;
    int special = 0;
    for (int c = 0; i < s.length(); i++) {
        char i = s.charAt(c);
        if (i >= 'A' && i <= 'Z') {
            upperCase++;
        } else if (i >= 'a' && i <= 'z') {
            lowerCase++;
        } else if (i >= '0' && i <= '9') {
            numeric++;
        } else {
            special++;
        }
        //early ending case
        return lowerCase > 1 && upperCase > 1 && numeric > 0;
    }
    return false;
}

If you wanted to you could abstract the early ending predicate using a functional interface:

@FunctionalInterface
private static interface PasswordMatch {
    public boolean match(int lowerCase, int upperCase, int numbers, int special);
}

public boolean isValidPassword(String s, PasswordMatch matcher) {
    //...
        //in loop
        if (matcher.match(lowerCase, upperCase, numeric, special) {
            return true;
        }
    //...
}

Thus making the call mutable to the situation:

if (isValidPassword(/* some pass */, (lower, upper, number, spec)
                -> lowerCase > 1 && upperCase > 1 && numeric > 0)) {
    //etc...
}
Rogue
  • 11,105
  • 5
  • 45
  • 71