简体   繁体   中英

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?

You can use .matches("[^AZ\\\\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
  • AZ 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.

Change your code to,

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

    return true;
}

Because matches function tries to match the whole string, you don't need to go for anchors. The above code would return false if the input string contains spaces or uppercase letters.

At its simplest, regular expression to match white space or capital letters is:

.*[A-Z\s].*

If any single such character will invalidate the input, then this will work nicely.

Normally, I would drop the .* at the start and end, but Java's String#matches() must match the entire string or else it fails, unlike the popular =~ operator in dynamic languages that will match any substring.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM