Max Nyirenda
Max Nyirenda

Reputation: 11

groovy split string by pipe and return substring index

I'm trying to split the header row of a pipe delimited text data file and return the index of two fields that could be in any position as the structure of our data varies from campaign to campaign. An example of my code is:

ArrayList list = new ArrayList()
def headingslist = "URN|BATCHID|CUST_URN|CUSTOMER_NAME|POSTCODE|PERSONKEY|MOBILENUMBER||PREMIUM|STATUS"
headingslist.split("\\|")

list.add(headingslist)

int indexMobNo = list.indexOf("MOBILENUMBER")
int indexURN = list.indexOf("PERSONKEY")

However, when I run this code or variations of it, I get the index returned as -1 as it can't find either substring in my string.

Upvotes: 1

Views: 1433

Answers (1)

Mene
Mene

Reputation: 3809

Calling split will not modify the value of headingslist but return a List. So you can either assign the result to list directly or use list.addAll to add all elements of the result to the list. Note that add would add the List itself as a new element to the List. So you would end up with a List that contains one element that is a List.

def headingslist = "URN|BATCHID|CUST_URN|CUSTOMER_NAME|POSTCODE|PERSONKEY|MOBILENUMBER||PREMIUM|STATUS"
ArrayList list = headingslist.split("\\|")

int indexMobNo = list.indexOf("MOBILENUMBER")
int indexURN = list.indexOf("PERSONKEY")

Upvotes: 2

Related Questions