smeeb
smeeb

Reputation: 29537

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?

Upvotes: 1

Views: 3491

Answers (3)

Guss
Guss

Reputation: 32354

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.

Upvotes: 1

PeterK
PeterK

Reputation: 1723

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.

Upvotes: 4

Avinash Raj
Avinash Raj

Reputation: 174776

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.

Upvotes: 0

Related Questions