Reputation: 11608
I need to check if a string contains any symbols other than a space. I cant check with
String.length() > 0
or
String.equals("")
since spaces are considered as characters. How can I find out whether a java String contains other characters (letters, symbols, numbers, whatever) ?
Upvotes: 1
Views: 8649
Reputation: 39536
Using Google Guava:
CharMatcher.WHITESPACE.negate().matchesAnyOf(str)
Upvotes: 2
Reputation: 2093
You can use StringUtils from apache commons: http://commons.apache.org/lang/api-3.1/index.html
Upvotes: 1
Reputation: 27880
Just trim()
the string (remember to check for null
before invoking a method on it):
Returns a copy of the string, with leading and trailing whitespace omitted.
myString != null && !myString.trim().isEmpty();
Or, if you're using Apache Commons, you can use StringUtils.isBlank(). You can check its implementation.
Upvotes: 6
Reputation: 8926
Remove all spaces:
String s = ...;
s = s.replaceAll("\\s+", "");
Then check the length:
if(s.length() > 0)
or check if a string is empty:
if (s.isEmpty())
Upvotes: 2
Reputation: 585
You could try something like this, to remove all the space characters and then to measure its length:
string.replaceAll("\\s","")
int length=string.length();
In this case, if length is greater than zero, it does contain non-space characters.
Hope this helps :)
Upvotes: 1
Reputation: 199
You can use
String.trim().equals("")
If String only contains spaces they all will be removed by trim()
before checking for equality
Upvotes: 3
Reputation: 15758
String test;
//populate test
if(test.trim().length() > 0)
{
//Bingo
}else{
//Uff
}
Upvotes: 2
Reputation: 272247
Whyn not use String.trim()
and check if the resultant length is greater than 0 ?
Upvotes: 2