list - 如何从列表中获取除与某些字符串相关的数字之外的所有数值

标签 list groovy

我想从字符串中获取除与字符串模式“SPN”相关的数字之外的所有数字

 def layoutStr = '1 ABC, 2 DEF, 3 SPN, 4 GHI'

 def splitted = layoutStr.split(',')
   *.trim()                        // remove white space from all the entries (note *)
   *.dropWhile { it ==~ /[^0-9 ]/ } // drop until you hit a char that isn't a letter or a space in the list
   .findAll { it[0] != 'SPN' }     // if a group starts with SPN, drop it

assert splitted == [1, 2, 4]

这似乎没有达到我预期的效果,我想我错过了重新收集步骤

最佳答案

您可以使用 findResults ,它仅收集不为 null 的元素,因此您可以使用它同时进行过滤和转换:

def layoutStr = '1 ABC, 2 DEF, 3 SPN, 4 GHI'

def splitted = layoutStr.split(',')
    *.trim()        // remove white space from all the entries (note *)
    *.split(/\s+/)  // Split all the entries on whitespace
    .findResults { it[1] == 'SPN' ? null : it[0] as Integer }

assert splitted == [1, 2, 4]

关于list - 如何从列表中获取除与某些字符串相关的数字之外的所有数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55424509/

相关文章:

java - 如何使用 EasyMock 模拟 Java.net.URL 类

python - 根据条件合并两个字典列表

java - 我们如何计算双向链表(循环列表)中的元素,其中我们不知道初始状态,也不知道头/尾在哪里‽

list - Web API 使用附加属性扩展列表

tomcat - 使用 WAR 文件在 Tomcat 服务器中部署 Grails 应用程序失败

java - JAR 插件实现

java - 外部化 DEFAULT 配置属性

jenkins - 我可以检查 Jenkinsfile 中是否存在环境变量

python - 生成满足特定条件的 7 个字母单词列表 - Python

Python:遍历字符串列表并使用 split()