Checking letter case (Upper/Lower) within a string in Java

后端 未结 9 555
闹比i
闹比i 2020-12-04 10:09

The problem that I am having is that I can\'t get my Password Verification Program to check a string to ensure that, 1 of the characters is in upper case and one is in lower

9条回答
  •  北荒
    北荒 (楼主)
    2020-12-04 10:57

    This is quite old and @SinkingPoint already gave a great answer above. Now, with functional idioms available in Java 8 we could give it one more twist. You would have two lambdas:

    Function hasLowerCase = s -> s.chars().filter(c -> Character.isLowerCase(c)).count() > 0;
    Function hasUpperCase = s -> s.chars().filter(c -> Character.isUpperCase(c)).count() > 0;
    

    Then in code we could check password rules like this:

    if (!hasUppercase.apply(password)) System.out.println("Must have an uppercase Character");
    if (!hasLowercase.apply(password)) System.out.println("Must have a lowercase Character");
    

    As to the other checks:

    Function isAtLeast8 = s -> s.length() >= 8; //Checks for at least 8 characters
    Function hasSpecial   = s -> !s.matches("[A-Za-z0-9 ]*");//Checks at least one char is not alpha numeric
    Function noConditions = s -> !(s.contains("AND") || s.contains("NOT"));//Check that it doesn't contain AND or NOT
    

    In some cases, it is arguable, whether creating the lambda adds value in terms of communicating intent, but the good thing about lambdas is that they are functional.

提交回复
热议问题