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

StringGroovyWhitespace

String Problem Overview


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.

String Solutions


Solution 1 - String

Another option is

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

(using Groovy Truth for Strings)

Solution 2 - String

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

Solution 3 - 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.

Thanks, -MH

Solution 4 - String

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"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncdeszaqView Question on Stackoverflow
Solution 1 - Stringtim_yatesView Answer on Stackoverflow
Solution 2 - StringdoelleriView Answer on Stackoverflow
Solution 3 - StringMostHatedView Answer on Stackoverflow
Solution 4 - Stringin_tranceView Answer on Stackoverflow