An Approach to Determine if a String Contains a Substring Using Groovy

Feedback

Question:

Is there a cool method to verify if a pattern matches a substring of
strings matches
?

To illustrate, I possess a collection of strings, either in the form of a list or an array.


def Errors = ['File xyz cannot be created: No space left on device', 'File kjh has errors: some_error']

I possess a collection of strings, one of which is exemplified by

def Patterns = ['Tests failed', 'No space left on device', 'Something goes wrong', ...some strings... ]

.

I want to confirm whether certain elements in List

Patterns

are present as substrings in elements of

Errors

.

The given example should output true since

Patterns

contains

No space left on device

and

Errors

contains

'File xyz cannot be created: No space left on device'

.

I am aware of a less efficient and visually unappealing approach using two for loops and the method

contains

. However, I am aware that Groovy offers more powerful built-in methods. I attempted to use

findAll()

, but it was unsuccessful.

Are there any ideas or methods to enhance its cleverness?


Solution:

Indicating specifically

pattern

and

error

:

patterns.find { pattern -> errors.find { error -> error.contains(pattern) } }  // -> No space left on device
patterns.any { pattern -> errors.find { error -> error.contains(pattern) } } // -> true

depending on your desired quantity or specific items to locate.

Or even shorter:

patterns.find { errors.find { error -> error.contains(it) } }
patterns.any { errors.find { error -> error.contains(it) } }

Frequently Asked Questions