Вместо того, чтобы манипулировать списком, вы можете обработать каждую запись в паре с ее преемником ... Я полагаю, что это делает то, что вы ищете?
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 number or space
.collate(2, 1, true) // group them with the next element in the list
.findAll { it[0] != 'SPN' } // if a group starts with SPN, drop it
.collect {
// If the successor is SPN add -EXT, otherwise, just return the element
it[1] == 'SPN' ? "${it[0]}-EXT" : it[0]
}
assert splitted == ['ABC', 'DEF-EXT', 'GHI']
Дополнительный вопрос
Чтобы просто получить их числа , а не SPN
:
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] } // Only keep those that don't have SPN
Обратите внимание, что это список строк, а не целых чисел ... Если вам нужны целые числа, то:
.findResults { it[1] == 'SPN' ? null : it[0] as Integer }