21

I need a Java regular expression, which checks that the given String is not Empty. However the expression should ingnore if the user has accidentally given whitespace in the beginning of the input, but allow whitespaces later on. Also the expression should allow scandinavian letters, Ä,Ö and so on, both lower and uppercase.

I have googled, but nothing seems ro quite fit on my needs. Please help.

Pradeep Singh
  • 3,582
  • 3
  • 29
  • 42
jaana
  • 295
  • 1
  • 3
  • 6

7 Answers7

24

You can also use positive lookahead assertion to assert that the string has atleast one non-whitespace character:

^(?=\s*\S).*$

In Java you need

"^(?=\\s*\\S).*$"
codaddict
  • 445,704
  • 82
  • 492
  • 529
  • 3
    +1 because sometimes it's still easier to use a regexp than a method. Ex: @Pattern for JSR-303 validation when Hibernate's @NotBlank can't be used. Nice job optimizing – Peter Davis Apr 12 '11 at 21:43
15

For a non empty String use .+.

Lavish
  • 151
  • 1
  • 2
5

This should work:

/^\s*\S.*$/

but a regular expression might not be the best solution depending on what else you have in mind.

sjngm
  • 12,423
  • 14
  • 84
  • 114
4
^\s*\S

(skip any whitespace at the start, then match something that's not whitespace)

The Archetypal Paul
  • 41,321
  • 20
  • 104
  • 134
4

For testing on non-empty input I use:

private static final String REGEX_NON_EMPTY = ".*\\S.*"; 
// any number of whatever character followed by 1 or more non-whitespace chars, followed by any number of whatever character 
javanna
  • 59,145
  • 14
  • 144
  • 125
2

You don't need a regexp for this. This works, is clearer and faster:

if(myString.trim().length() > 0)
Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
-3

It's faster to create a method for this rather than using regular expression

/**
 * This method takes String as parameter
 * and checks if it is null or empty.
 * 
 * @param value - The value that will get checked. 
 * Returns the value of "".equals(value). 
 * This is also trimmed, so that "     " returns true
 * @return - true if object is null or empty
 */
public static boolean empty(String value) {
    if(value == null)
        return true;

    return "".equals(value.trim());
}
Shervin Asgari
  • 23,901
  • 30
  • 103
  • 143