Reputation: 295
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.
Upvotes: 21
Views: 55633
Reputation: 41
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
Upvotes: 4
Reputation: 454960
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).*$"
Upvotes: 24
Reputation: 24499
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());
}
Upvotes: -3
Reputation: 346260
You don't need a regexp for this. This works, is clearer and faster:
if(myString.trim().length() > 0)
Upvotes: 2
Reputation: 12861
This should work:
/^\s*\S.*$/
but a regular expression might not be the best solution depending on what else you have in mind.
Upvotes: 5
Reputation: 41749
^\s*\S
(skip any whitespace at the start, then match something that's not whitespace)
Upvotes: 4