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.

1
  • 3
    str.trim().equals("")? Commented Dec 15, 2010 at 10:18

7 Answers 7

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).*$"
Sign up to request clarification or add additional context in comments.

1 Comment

+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
15

For a non empty String use .+.

Comments

5

This should work:

/^\s*\S.*$/

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

1 Comment

@jaana: This answer is in JavaScript syntax; in Java it would be "^\\s*\\S.*$".
4
^\s*\S

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

4 Comments

It does not allow whitespaces later on?
Depends if you match against the whole string or not. If you want to match against the whole string, add .*$ to the end. But unless you must use a regex, as others have pointed out, trim is more direct.
In fact even bare \S is enough. You do not need any anchors at start it either contains non-whitespace somewhere or not.
@Muxecoid, yep, that's even simpler
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 

Comments

2

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

if(myString.trim().length() > 0)

Comments

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

1 Comment

what about String.IsNullOrEmpty(value) ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.