21

I know that I could do this with a series of for loops that iterate through the string but that would be terrible programming. Well, my professor prefers I don't do it this way. I'd like to use regular expressions to do this.

Michael Drum
  • 821
  • 2
  • 11
  • 24
  • So what's stopping you from using regular expressions to do this? – t0mppa Oct 31 '16 at 04:00
  • 3
    I don't know how. – Michael Drum Oct 31 '16 at 04:01
  • 6
    You don't know how to write a regexp or how to use regexp to check if a `String` matches it? Tutorials of both should be very easily found out by a search via your favorite search engine. – t0mppa Oct 31 '16 at 04:04
  • @MichaelDrum : See http://stackoverflow.com/questions/5892115/whats-the-time-complexity-of-average-regex-algorithms . In terms of time complexity, Regex behaves same as a simple linear search . In worst case, regex may behave badly. Point is, your case is too simple to look into regex. There seems to be no specific advantage to it anyway for me. – CyprUS Oct 31 '16 at 04:06
  • Why is it "terrible programming"? It's probably going to be at least as efficient, likely more so. – Louis Wasserman Oct 31 '16 at 04:07
  • Start with the [relevant section of the manual](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#matches(java.lang.String)) – dave Oct 31 '16 at 04:08

7 Answers7

29

For a simple string check, a single sweep through the string is enough. Since Regex will not offer any significant benefit, here is a simple for loop to achieve the same :

private static boolean checkString(String str) {
    char ch;
    boolean capitalFlag = false;
    boolean lowerCaseFlag = false;
    boolean numberFlag = false;
    for(int i=0;i < str.length();i++) {
        ch = str.charAt(i);
        if( Character.isDigit(ch)) {
            numberFlag = true;
        }
        else if (Character.isUpperCase(ch)) {
            capitalFlag = true;
        } else if (Character.isLowerCase(ch)) {
            lowerCaseFlag = true;
        }
        if(numberFlag && capitalFlag && lowerCaseFlag)
            return true;
    }
    return false;
}

Test run:

System.out.println(checkString("aBCd1")); // output is true
System.out.println(checkString("abcd")); //output is false

I think this should help OP's particular problem.

CyprUS
  • 3,931
  • 7
  • 43
  • 85
  • so if i do this: `System.out.println(checkString("A"));` and i do this `System.out.println(checkString("a"));` i recieve the same output -> `false` – ermp Feb 11 '21 at 14:20
15

Example of @goshDeveloper's answer.

First create a Pattern variable with regular expression you want.

public final Pattern textPattern = Pattern.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).+$");

Second you can use it like this:

public boolean isTextValid(String textToCheck) {
return textPattern.matcher(textToCheck).matches();
}
Yhondri
  • 530
  • 1
  • 5
  • 10
  • 1
    And what pattern could this be for French and/or Spanish or ... ? https://stackoverflow.com/a/4052294/731548 – cquezel Aug 06 '20 at 16:38
12

Using Java 9:

public boolean isValid(String value) {
    return containsLowerCase(value) && 
           containsUpperCase(value) && 
           containsNumber(value);
}

private boolean containsLowerCase(String value) {
    return contains(value, i -> Character.isLetter(i) && Character.isLowerCase(i));
}

private boolean containsUpperCase(String value) {
    return contains(value, i -> Character.isLetter(i) && Character.isUpperCase(i));
}

private boolean containsNumber(String value) {
    return contains(value, Character::isDigit);
}

private boolean contains(String value, IntPredicate predicate) {
    return value.chars().anyMatch(predicate);
}
Łukasz K
  • 454
  • 5
  • 9
  • 3
    I like the readability of your solution. Performance-wise I dislike that every new condition requires an additional iteration over the value. Not a big issue on small / medium strings of course, but something to consider. – Roland van der Linden Dec 31 '18 at 09:07
  • This solution works in JAVA8 too. – Frighi Apr 16 '21 at 08:10
11

Try regular expression

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$

descriptions are as follow
(?=.*[a-z])  -- check lower case letter
(?=.*[A-Z]) -- check upper case letter
(?=.*\d) -- check one digit exists
Ghost Developer
  • 915
  • 1
  • 7
  • 15
  • Thank you. This looks very promising. However, I have no experience with regex. Let's say I'd like to know if String _text_ contains at least one lower case letter, one upper case, and a number. How would I write that in the form of an 'if' statement? – Michael Drum Oct 31 '16 at 04:11
  • 2
    follow this tutorial https://www.tutorialspoint.com/java/java_regular_expressions.htm – Ghost Developer Oct 31 '16 at 04:14
  • 1
    Are'nt these valid letters in french and spanish? aAàÀâÂæÆbBcCçÇdDeEéÉèÈêÊëËfFgGhHiIîÎïÏjJkKlLmMnNñÑoOôÔœŒpPqQrRsStTuUùÙûÛüÜvVwWxXyYÿŸzZáÁíÍóÓúÚ And what pattern could this be for French and/or Spanish or ... ? https://stackoverflow.com/a/4052294/731548 – cquezel Aug 06 '20 at 16:34
8

you can use :

public static boolean isTextContainUpperCase(String text) {
       if (StringUtils.isEmpty(text)) {
              return false;
       }
       return !text.equals(text.toLowerCase());
}
David Karlsson
  • 7,621
  • 8
  • 49
  • 94
sopheamak
  • 325
  • 2
  • 10
  • Dude, this is the wrong answer if the text parameter characters already lower cased, it will also return true, for example `isTextContainUpperCase("a text");` will return true although it does not contains upper case character at all – HendraWD Aug 30 '18 at 08:21
  • 2
    Edit the if statement to !text.equals(text.toLowerCase()) and it will probably do what you ask (I edited the code in the answer) – David Karlsson Oct 02 '18 at 08:26
3

If you are looking to check whether your string contains uppercase letter or not, you can use below pattern:

String s="abcDe_shdgwU";    //you can have any String here

if(s.matches(".*[A-Z].*"))
   System.out.println("The String contains Uppercase letter(s)");
else
  System.out.println("does not contain Uppercase letter(s)");

Hope that helps. Thank you. Regards, Tanumay Saha

0

You can use Character class of java. So for lowercase, Character.isLowerCase(ch) Character.isUpperCase(ch). For this you have to iterate over the string. I know that bit is irrelevant to you, however you can use "\\d+" for numbers in a string.

Saad
  • 369
  • 6
  • 22