在 Java 中匹配非空白
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3824438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Matching non-whitespace in Java
提问by george smiley
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
但它似乎不起作用。有没有人有什么建议?我知道我可以修剪字符串并测试它是否等于空字符串,但我宁愿这样做
回答by Stefan Kendall
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 findmethod will search for partial matches, versus a complete match. This seems to be the behavior you need.
该find方法将搜索部分匹配,而不是完全匹配。这似乎是您需要的行为。
回答by Gabriel
city.matches(".*\S.*")
or
或者
Pattern nonWhitespace = Pattern.compile(".*\S.*")
nonWhitspace.matches(city)
回答by Sheldon L. Cooper
\S(uppercase s) matches non-whitespace, so you don't have to negate the result of matches.
\S(大写 s)匹配非空格,因此您不必否定matches.
Also, try Matcher's method findinstead of Pattern.matches.
另外,尝试使用 Matcher 的方法find而不是Pattern.matches.
回答by ColinD
Guava's CharMatcherclass is nice for this sort of thing:
Guava的CharMatcher类非常适合这种事情:
boolean hasNonWhitespace = !CharMatcher.WHITESPACE.matchesAllOf(someString);
This matches whitespace according to the Unicode standard rather than using Java's Character.isWhitespace()method... CharMatcher.JAVA_WHITESPACEmatches according to that.
这根据 Unicode 标准匹配空白,而不是使用 Java 的Character.isWhitespace()方法……CharMatcher.JAVA_WHITESPACE根据那个进行匹配。

