Search code examples
javaregexwhitespacecasing

Java regex to find whitespaces or upper-case characters


I have a method that validates a string and makes sure it doesn't have any whitespaces or upper-case characters:

boolean validate(String input) {
    if(input.matches(".*\\S.*([A-Z]+)")) {
        return false;
    }

    return true;
}

Unfortunately, when I run this, it simply doesn't work. It doesn't throw any exceptions, it just allows all input string ("HelloWorld", "hello world", "Hello world", etc.) to pass validation. Any ideas where I'm going wrong?


Solution

  • You can use .matches("[^A-Z\\s]+")

    It will return true if your string does not contain any upper case characters or white space characters.

    Explanation

    the bit between [...] is called a character class, it matches all characters provided

    • ^ makes it negative, so it matches everything not provided
    • A-Z is the range of upper case characters
    • \\s is short hand for any white space character
    • + ensures that your string is at least 1 character or more.