我想从字符串中获取除与字符串模式“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/