2

I would like to split this text contact into 3 parts separated by -.

In each part we have: name, function, number and email.

Then I'd like to separate each part by \n.

def contact = '''name1
Function1
: 1111
: name1@mail.com-name2 
Function2
: 2222
: name2@mail.com-name3
Function3
: 3333
: name3@mail.com
''' 

I've tried this:

def contact_part = contact.split('-')
println contact_part[0]
def data = contact_part.split('\n') //line 15
println data[1]

But I got this error:

groovy.lang.MissingMethodException: No signature of method: [Ljava.lang.String;.split() is applicable for argument types: (java.lang.String) values: [ ] Possible solutions: split(groovy.lang.Closure), wait(), sort(), init(), tail(), toList() at Script1.run(Script1.groovy:15)

Thank you.

Szymon Stepniak
  • 40,216
  • 10
  • 104
  • 131
Wijdane
  • 23
  • 3

1 Answers1

1

You got this exception, because you have called .split() on String[]. The first split creates an array of strings, so the next split has to be applied on each element of this array. Consider following example:

def contact = '''name1
Function1
: 1111
: name1@mail.com-name2 
Function2
: 2222
: name2@mail.com-name3
Function3
: 3333
: name3@mail.com
'''

contact.split('-').each { part ->
    def data = part.split('\n').toList()

    println "name: ${data[0]}, function: ${data[1]}, number: ${data[2].replace(': ', '')}, email: ${data[3].replace(': ', '')}"
}

We split input string by - and then each part got split by \n. For each split part we print console output like:

name: name1, function: Function1, number: 1111, email: name1@mail.com
name: name2 , function: Function2, number: 2222, email: name2@mail.com
name: name3, function: Function3, number: 3333, email: name3@mail.com

Note that I've added .replace(': ', '') to clean number and email values.

Szymon Stepniak
  • 40,216
  • 10
  • 104
  • 131
  • Thank you so much. It works well. Please, if "name" is a sentence with two word separated by space " ", like this:"lastname firstname" How can I get the lastname, and the firstname? – Wijdane Mar 29 '18 at 16:01
  • That's okey, I solved the second problem. Since "${data[0]}" is a string, so I can apply the split method: def lastname = "${data[0]}".split(' ')[0] def firstname = "${data[0]}".split(' ')[1] println lastname println firstname – Wijdane Mar 29 '18 at 18:15