sdgd
sdgd

Reputation: 733

Trim the names in the list using Groovy

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

Answers (3)

cfrick
cfrick

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

tim_yates
tim_yates

Reputation: 171184

Or

def list = ['My_name_is_Jack', 'My_name_is_Rock', 'My_name_is_Sunn']

println list*.split('_')*.getAt(-1)

Upvotes: 3

Rao
Rao

Reputation: 21389

Here you go with either one of the approach.

  • You can use sustring with lastIndexOf
  • or replace method to remove My_name_is_ with empty string

Script (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

Related Questions