How to check if a string contains uppercase java

Viewed 2068

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?

7 Answers

With streams, you can to the following.

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

This is much lighter than regexes in terms of resources.

Just use the proper regex with matcher.find()

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

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

You can do it as follows:

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(".*[A-Z].*")) {
                System.out.println("'" + key + "' contains invalid, key contains a space, illegal character");
            } else {
                System.out.println("'" + key + "' passed the check");
            }
        }
    }
}

Output:

'HELLO' contains invalid, key contains a space, illegal character
'Hello' contains invalid, key contains a space, illegal character
'hello' passed the check
'hello world' passed the check
'Hello World' contains invalid, key contains a space, illegal character

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
}

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