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

List 如何从列表中获取除与某些字符串相关的数字以外的所有数值,list,groovy,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 u

我想从字符串中获取所有数字,但与字符串模式“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
,它只收集非空的元素,因此您可以使用它同时进行过滤和转换:

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]