Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching non-whitespace in Java

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

like image 803
george smiley Avatar asked Sep 29 '10 17:09

george smiley


3 Answers

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.

like image 172
Stefan Kendall Avatar answered Oct 13 '22 17:10

Stefan Kendall


city.matches(".*\\S.*")

or

Pattern nonWhitespace = Pattern.compile(".*\\S.*")
nonWhitspace.matches(city)
like image 42
Gabriel Avatar answered Oct 13 '22 17:10

Gabriel


\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.

like image 42
Sheldon L. Cooper Avatar answered Oct 13 '22 19:10

Sheldon L. Cooper