louistcooper
louistcooper

Reputation: 43

How to check if a string contains uppercase java

I am working on a program that lets a user input an alphanumeric key, and checks if it is a valid key against some criteria, one of these is whether or not the key contains an uppercase. TThis is what I have tried so far:

else if (key.contains("QWERTYUIOPASDFGHJKLZXCVBNM")){
    UI.println("Invalid, key contains a space, illegal character");
    }

This only detects the capital letters if they are written in this order. is there a command such as key.contains i should be using?

Upvotes: 3

Views: 3640

Answers (7)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79075

You can use String#matches with the regex, .*\p{Lu}.*. Learn more about Pattern from the documentation.

Demo:

public class Main {
    public static void main(String args[]) {
        String[] keys = { "HELLO", "Hello", "hello", "hello world", "Hello World" };
        for (String key : keys) {
            if (key.matches(".*\\p{Lu}.*")) {
                System.out.println(key + " => Invalid");
            } else {
                System.out.println(key + " => Valid");
            }
        }
    }
}

Output:

HELLO => Invalid
Hello => Invalid
hello => Valid
hello world => Valid
Hello World => Invalid

Alternatively,

You can check the presence of an uppercase letter using the regex, \p{Lu}.

Demo:

import java.util.regex.Pattern;

public class Main {
    public static void main(String args[]) {
        String[] keys = { "HELLO", "Hello", "hello", "hello world", "Hello World" };
        for (String key : keys) {
            if (Pattern.compile("\\p{Lu}").matcher(key).find()) {
                System.out.println(key + " => Invalid");
            } else {
                System.out.println(key + " => Valid");
            }
        }
    }
}

Upvotes: 1

Tobias Näth
Tobias Näth

Reputation: 1

If you took the streams solution of @OlivierGrégoire and want limit it to the Capitals [A-Z] you can get it by also testing the UnicodeBlock as BASIC_LATIN. Where BASIC_LATIN is the ASCII Block of Unicode(see BASIC_LATIN )

        key.chars().anyMatch(this::isBasicLatinCapital)
        ...
        private boolean isBasicLatinCapital( int c) {
        return
            Character.UnicodeBlock.BASIC_LATIN == Character.UnicodeBlock.of(c) && Character.isUpperCase(c) ;
        } 
        

Upvotes: 0

Olivier Grégoire
Olivier Grégoire

Reputation: 35427

If you use Guava, you can get it using the powerful CharMatcher:

First compile the matcher as a static member of the class so that it's done once and you don't need to recompute it at every call.

private static final CharMatcher UPPERCASE_LETTER = CharMatcher.inRange('A', 'Z');

Change it to whatever letters you actually want. For instance if you want some accentuated characters, you can extend the following:

private static final CharMatcher UPPERCASE_LETTER = CharMatcher.inRange('A', 'Z')
                                                               .or(CharMatcher.anyOf("ÁÀÄÂÉÈËÊÍÌÏÎÓÒÖÔÚÙÜÛ"));

If you're lazy and just want to delegate to Character::isUpperCase, that's also possible:

private static final CharMatcher UPPERCASE_LETTER = CharMatcher.forPredicate(Character::isUpperCase)

Then in your code, write the following:

if (UPPERCASE_LETTER.matchesAnyOf(key)) {
  // Do what you want
}

Upvotes: 1

Daniel
Daniel

Reputation: 1037

You can use Apache Commons Lang (https://commons.apache.org/proper/commons-lang/). Is has a method for this:

else if (StringUtils.containsAny(key, "QWERTYUIOPASDFGHJKLZXCVBNM")){
    UI.println("Invalid, key contains a space, illegal character");
}

Upvotes: 1

Maurice
Maurice

Reputation: 7381

Or you can do it as described by sopheamak here: How do I check if a Java String contains at least one capital letter, lowercase letter, and number?

In your example that would be:

else if (!key.equals(key.toLowerCase())

If one of the letters in key is uppercase it will not match the result of key.toLowerCase() and thus return true because of !.

Upvotes: 2

Olivier Grégoire
Olivier Grégoire

Reputation: 35427

With streams, you can to the following.

key.chars().anyMatch(Character::isUpperCase)

This is much lighter than regexes in terms of resources.

Upvotes: 5

m.antkowicz
m.antkowicz

Reputation: 13571

Just use the proper regex with matcher.find()

Pattern.compile("[A-Z]").matcher(key).find()

Upvotes: 2

Related Questions