在 Groovy 中如何确定字符串是否非空且不仅仅是空格?
Groovy 将 isAllWhitespace()
方法添加到字符串中,这很棒,但似乎没有一个好的方法来确定字符串是否具有 以外的内容>只是其中的空白。
我能想到的最好的办法是:
myString && !myString.allWhitespace
但这似乎太冗长了。这对于验证来说似乎是很常见的事情,因此必须有一种更简单的方法来确定这一点。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
另一种选择是
(使用 Groovy Truth for Strings)
Another option is
(using Groovy Truth for Strings)
您可以向 String 添加一个方法以使其更具语义:
这可以让您这样做:
You could add a method to String to make it more semantic:
which let's you do:
它适用于我的 grails2.1 项目:
如果 someObj.getSomeStr() 为 null 或空“” -> str = "默认值"
如果 someObj.getSomeStr() = "someValue" -> str =“某个值”
It's works in my project with grails2.1:
If someObj.getSomeStr() is null or empty "" -> str = "Default value"
If someObj.getSomeStr() = "someValue" -> str = "someValue"
我发现这种方法快速且通用:
不过,我对使用 Groovy 还很陌生,所以我不确定是否存在一种方法可以使其成为
String
类型的实际扩展方法,并且这个效果很好,我都懒得去看了。I find this method to be quick and versatile:
I am quite new to using Groovy, though, so I am not sure if there exists a way to make it an actual extension method of the
String
type and this works well enough that I have not bothered to look.