在 Groovy 中,如何确定 String 是否为非空而不仅仅是空格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9168518/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:22:01  来源:igfitidea点击:

How can I determine if a String is non-null and not only whitespace in Groovy?

stringgroovywhitespace

提问by cdeszaq

Groovy adds the isAllWhitespace()method to Strings, which is great, but there doesn't seem to be a goodway of determining if a String has something other than justwhite space in it.

Groovy的添加isAllWhitespace()方法为字符串,这是伟大的,但似乎没有成为一个很好的判断字符串是否具有比其他东西的方式只是在它的空白。

The best I've been able to come up with is:

我能想到的最好的是:

myString && !myString.allWhitespace

But that seems too verbose. This seems like such a common thing for validation that there mustbe a simpler way to determine this.

但这似乎太冗长了。这对于验证来说似乎是一件很常见的事情,因此必须有一种更简单的方法来确定这一点。

回答by tim_yates

Another option is

另一种选择是

if (myString?.trim()) {
  ...
}

回答by doelleri

You could add a method to String to make it more semantic:

您可以向 String 添加一个方法以使其更具语义:

String.metaClass.getNotBlank = { !delegate.allWhitespace }

which let's you do:

让你做:

groovy:000> foo = ''
===> 
groovy:000> foo.notBlank
===> false
groovy:000> foo = 'foo'
===> foo
groovy:000> foo.notBlank
===> true