views:

83

answers:

3

I would like to detect strings that have non-whitespace characters in them. Right now I am trying:

!Pattern.matches("\\*\\S\\*", city)

But it doesn't seem to be working. Does anyone have any suggestions? I know I could trim the string and test to see if it equals the empty string, but I would rather do it this way

+1  A: 

\S (uppercase s) matches non-whitespace, so you don't have to negate the result of matches.

Also, try Matcher's method find instead of Pattern.matches.

Sheldon L. Cooper
+1  A: 

What exactly do you think that regex matches?

Try

Pattern p = Pattern.compile( "\\S" );
Matcher m = p.matcher( city );
if( m.find() )
//contains non whitespace

The find method will search for partial matches, versus a complete match. This seems to be the behavior you need.

Stefan Kendall
I was hoping it would match "anything, followed by a non-whitespace character, followed by anything."
george smiley
A: 

Guava's CharMatcher class is nice for this sort of thing:

boolean hasNonWhitespace = !CharMatcher.WHITESPACE.matchesAllOf(someString);

This matches whitespace according to the Unicode standard rather than using Java's Character.isWhitespace() method... CharMatcher.JAVA_WHITESPACE matches according to that.

ColinD