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
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());
}
This should work:
/^\s*\S.*$/
but a regular expression might not be the best solution depending on what else you have in mind.
^\s*\S
(skip any whitespace at the start, then match something that's not whitespace)
For a non empty String use .+
.
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
You don't need a regexp for this. This works, is clearer and faster:
if(myString.trim().length() > 0)