Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy split on period and return only first value

Tags:

groovy

I have the input as

var = primarynode.domain.local

and now I Need only primarynode from it.

I was looking both split and tokenize but not able to do it in one line code. does anyone know how to do it in one line code?

like image 690
ro ra Avatar asked Sep 28 '16 11:09

ro ra


People also ask

How do you split a string only on the first instance of specified character?

Use the String. split() method with array destructuring to split a string only on the first occurrence of a character, e.g. const [first, ... rest] = str. split('-'); .

How do you split a string with a period?

To split a string with dot, use the split() method in Java. str. split("[.]", 0);

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".


2 Answers

Well assuming that you want to just get the first word(before . ) from the input string.

You can use the tokenize operator of the String

If you have

def var = "primarynode.domain.local"

then you can do

def firstValue = ​var.tokenize(".")[0]​
println firstValue

output

primarynode
like image 51
Prakash Thete Avatar answered Oct 07 '22 19:10

Prakash Thete


The split method works, you just have to be aware that the argument is a regular expression and not a plain String. And since "." means "any character" in a regular expression, you'll need to escape it...

var = 'primarynode.domain.local'.split(/\./)[0]

...or use a character class (the "." is not special inside a character class)

var = 'primarynode.domain.local'.split(/[.]/)[0]
like image 40
bdkosher Avatar answered Oct 07 '22 20:10

bdkosher