Reputation: 733
I have a list in Groovy
which contains the names in the below format:
How can I trim the list and get only the last part of it; i.e. Names - Jack, Rock and Sunn
. (Please note that the names are only 4 characters long)
Upvotes: 0
Views: 496
Reputation: 37063
You can either remove the common prefix:
def names = [ "My_name_is_Jack", "My_name_is_Rock", "My_name_is_Sunn", ]
assert ['Jack', 'Rock', 'Sunn'] == names*.replaceFirst('My_name_is_','')
or since you are actually interrested in the last four chars, you can also take those:
assert ['Jack', 'Rock', 'Sunn'] == names*.getAt(-4..-1)
Upvotes: 1
Reputation: 171184
Or
def list = ['My_name_is_Jack', 'My_name_is_Rock', 'My_name_is_Sunn']
println list*.split('_')*.getAt(-1)
Upvotes: 3
Reputation: 21389
Here you go with either one of the approach.
lastIndexOf
replace
method to remove My_name_is_
with empty stringScript (using the first approach):
def list = ['My_name_is_Jack', 'My_name_is_Rock', 'My_name_is_Sunn']
//Closure to get the name
def getName = { s -> s.substring(s.lastIndexOf('_')+1, s.size()) }
println list.collect{getName it}
If you want to use replace
, then use below closure.
def getName = { s -> s.replace('My_name_is_','') }
You can quickly try it online demo
Upvotes: 3