在 Groovy 中是否有一种方法可以遍历数组并找到字符串的特定部分并将字符串的整个部分存储在另一个变量中

In Groovy is there a way to iterate over an array and find specific part of the string and store the entire part of the string in another variable

试图找到一种方法来遍历数组,查找或匹配字符串的某些部分,如果字符串与模式匹配,则将整个字符串复制到一个新变量中,请找到以下代码段

def sample_example_array = ["Sample6" , "Sample231001", "xyz", "abc","Sample3\Example1"]
// Need to iterate over the array by checking each element in the array look for String Example
// I tried find to find the first element matching the criteria
def new_string_sample_example = sample_example_array.find { sample_example_array.contains("Example1") }
println "Post Searching Matching the new variable is:" + new_string_sample_example

结果为NULL,

任何人都可以建议我如何用 Groovy

实现这一点

预期结果是Post搜索匹配新变量是:Sample3\Example1

如果您将代码更改为:

def sample_example_array = ["Sample456" , "Sample231001", "xyz", "abc","Sample123Example1"]
// Need to iterate over the array by checking each element in the array look for String Example
// I tried find to find the first element matching the criteria
def new_string_sample_example = sample_example_array.find { it.contains("Example1") }
println "Post Searching Matching the new variable is:" + new_string_sample_example

应该可以。换句话说,更改 find { ... } 闭包中的内容以引用 it 变量,该变量将迭代地分配给数组中的每个值。

在 groovy 中,对于接受一个参数(像这个)的闭包(即 curlie 块 {...}),您可以执行以下任一操作:

[1,3,4].find { it < 4 }
// or
[1,3,4].find { n -> n < 4 }

它们是等价的。

执行上面的固定代码给出:

─➤ groovy solution.groovy
Post Searching Matching the new variable is:Sample123Example1