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

时间:2019-03-29 19:41:22

标签: 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]

这似乎没有按照我的预期去做,我想我错过了重新收集的步骤

1 个答案:

答案 0 :(得分:3)

您可以使用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]