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

核能气质少年 提交于 2020-04-05 07:42:10

问题


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

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 must be a simpler way to determine this.


回答1:


Another option is

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



回答2:


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

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


来源:https://stackoverflow.com/questions/9168518/how-can-i-determine-if-a-string-is-non-null-and-not-only-whitespace-in-groovy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!