在Groovy中,如何仅从列表中提取匹配字符串?

发布于 2025-02-07 10:27:38 字数 818 浏览 1 评论 0原文

在我的groovy脚本中,我有以下列表

subList = ["foo", "bar", "baz"]

,文本文件master_list.txt带有以下内容:

MASTER_STRING="ping:123 foo:321 pong:999 bar:888"
OTHER_STRING=helloWorld

我需要获取唯一的匹配项表单master_string,因此上面的示例,我需要获得一个列表 [“ foo:321”,“ bar:888”]

我对Groovy非常新,我可以找到是否在Master_list中找到的匹配sub字符串,该字符串中的代码> sublist ,但是如何将所需的字符串提取为列表?

props = readProperties file: "master_list.txt"
boolean exists = false
if (props.containsKey('MASTER_STRING')) {
   def masterList = props.MASTER_STRING.split(/ /)
   exists = masterList.findAll { a ->
       subList.any { a.contains(it)}
   }
}
if (exists) {
   println "at least one item exists" // Here I like to print ["foo:321", "bar:888"]
}

In my groovy script, I have a list like below

subList = ["foo", "bar", "baz"]

and a text file master_list.txt with below content:

MASTER_STRING="ping:123 foo:321 pong:999 bar:888"
OTHER_STRING=helloWorld

I need to get the only the matching items form MASTER_STRING, so from above example, I need to get a list like
["foo:321", "bar:888"]

I am very new to groovy, I could find if a matching sub string found in MASTER_LIST which is there in subList, but how to extract the required strings as list?

props = readProperties file: "master_list.txt"
boolean exists = false
if (props.containsKey('MASTER_STRING')) {
   def masterList = props.MASTER_STRING.split(/ /)
   exists = masterList.findAll { a ->
       subList.any { a.contains(it)}
   }
}
if (exists) {
   println "at least one item exists" // Here I like to print ["foo:321", "bar:888"]
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

你的笑 2025-02-14 10:27:38

用读取文件显示它,而不是有2个列表。

masterList= ['aaa:123','bbb:002','ggg:003']
subList = ['aaa:', 'bbb:']
println masterList.findAll {
   a -> subList.any { a.contains(it)}
}

打印[AAA:123,BBB:002],这就是我想要的,我在问题中对此非常复杂。感谢@matt的评论。

Showing it withoug reading files, instead having 2 lists.

masterList= ['aaa:123','bbb:002','ggg:003']
subList = ['aaa:', 'bbb:']
println masterList.findAll {
   a -> subList.any { a.contains(it)}
}

prints [aaa:123, bbb:002] and this is what I want, I overly complicated this in my question. thanks @Matt for your comment.

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