intargc
intargc

Reputation: 3111

What is the best way to get two parts of a Groovy string?

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?

Upvotes: 1

Views: 176

Answers (2)

Ted Naleid
Ted Naleid

Reputation: 26801

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.

Upvotes: 2

ccheneson
ccheneson

Reputation: 49410

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

Upvotes: 1

Related Questions