Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting last word in a tokenized string in groovy

Tags:

A basic String handling question..I have a tokenized String like val1.val2.val3.....valN How do I get the last word valN from the string above.

like image 847
pri_dev Avatar asked Mar 12 '12 00:03

pri_dev


People also ask

How do I get the last word in a String?

To get the last word of a string:Call the split() method on the string, passing it a string containing an empty space as a parameter. The split method will return an array containing the words in the string. Call the pop() method to get the value of the last element (word) in the array.

How do I truncate a String in Groovy?

The Groovy community has added a take() method which can be used for easy and safe string truncation. Both take() and drop() are relative to the start of the string, as in "take from the front" and "drop from the front". Save this answer.


1 Answers

If you pass a negative index n to the subscript operator in a List, you get n-th last element. Therefore, the -1 element is the last one:

def words = 'val1.val2.val3' def last = words.tokenize('.')[-1] assert last == 'val3' 

Update: You also have the, arguably more readable, last method:

def last = words.tokenize('.').last() 
like image 97
epidemian Avatar answered Oct 20 '22 04:10

epidemian