Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if substring of string's array match to patterns from other string array

Tags:

groovy

I wonder if there is any groovy-way to check if substring of strings matches to patterns.

For example I have strings List (or array):

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

Then I have list of strings, for example def Patterns = ['Tests failed', 'No space left on device', 'Something goes wrong', ...some strings... ]

I would like to check if some elements of List Patterns are substrings of Errors elements .

In that example it should return true, because Patterns has No space left on device and Errors has 'File xyz cannot be created: No space left on device'.

I know how to write it very ulgy and not efficient by using two for loops and method contains, but I know that Groovy has much more powerfull built-in methods. I have tried with findAll(), but it doesnt worked at all.

Do you have any ideas? Is there any way to make it more clever?

like image 828
Ojmeny Avatar asked Sep 28 '22 00:09

Ojmeny


1 Answers

Explicitly naming 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 what/how many you want to find.

Or even shorter:

patterns.find { errors.find { error -> error.contains(it) } }
patterns.any { errors.find { error -> error.contains(it) } }
like image 67
jalopaba Avatar answered Oct 06 '22 18:10

jalopaba