views:

48

answers:

2

If I have a string in Groovy like so...

'user.company.name'

... and I want to get the the word "company" and "name" from that string, what is the best way to go about it?

I was thinking of something like this, but I'm not sure if it's the most efficient/groovy way:

def items = 'user.company.name'.tokenize('.')
def company = items[-2]
def name = items[-1]

Is there a better way to do this?

+1  A: 

You could also use split() that will return an array of String. tokenize() returns a List so I would use it if I need to iterate through the tokens.

items = 'user.company.name'.split('\\.')
company = items[1]
name = items[2]

See the link here for the description of those 2 String methods

ccheneson
+2  A: 

One alternative if you're always looking for the last 2 sections of the string would be to use a regex like this:

'user.company.name'.find(/(.*)\.(.*)\.(.*)/) { full, user, company, name ->
    assert user == "user"
    assert company == "company"
    assert name == "name"
}

One advantage to this is that you don't need to worry about array index exceptions if the string doesn't have the "user.company.name" format. If the regex doesn't match, the closure won't be executed.

Ted Naleid