在 Groovy 中如何确定字符串是否非空且不仅仅是空格?

发布于 2025-01-03 05:32:27 字数 265 浏览 1 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

灰色世界里的红玫瑰 2025-01-10 05:32:27

另一种选择是

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

(使用 Groovy Truth for Strings

Another option is

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

(using Groovy Truth for Strings)

也只是曾经 2025-01-10 05:32:27

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

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

这可以让您这样做:

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

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
世界和平 2025-01-10 05:32:27

它适用于我的 grails2.1 项目:

String str = someObj.getSomeStr()?.trim() ?: "Default value"

如果 someObj.getSomeStr() 为 null 或空“” -> str = "默认值"
如果 someObj.getSomeStr() = "someValue" -> str =“某个值”

It's works in my project with grails2.1:

String str = someObj.getSomeStr()?.trim() ?: "Default value"

If someObj.getSomeStr() is null or empty "" -> str = "Default value"
If someObj.getSomeStr() = "someValue" -> str = "someValue"

勿忘初心 2025-01-10 05:32:27

我发现这种方法快速且通用:

static boolean isNullOrEmpty(String str) { return (str == null || str.allWhitespace) } 

// Then I often use it in this manner
DEF_LOG_PATH = '/my/default/path'
logPath = isNullOrEmpty(log_path) ? DEF_LOG_PATH : log_path

不过,我对使用 Groovy 还很陌生,所以我不确定是否存在一种方法可以使其成为 String 类型的实际扩展方法,并且这个效果很好,我都懒得去看了。

I find this method to be quick and versatile:

static boolean isNullOrEmpty(String str) { return (str == null || str.allWhitespace) } 

// Then I often use it in this manner
DEF_LOG_PATH = '/my/default/path'
logPath = isNullOrEmpty(log_path) ? DEF_LOG_PATH : log_path

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文