简体   繁体   English

groovy通过管道拆分字符串并返回子字符串索引

[英]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. 但是,当我运行此代码或其变体时,由于找不到字符串中的任何子字符串,因此索引返回为-1。

Calling split will not modify the value of headingslist but return a List. 调用split不会修改headingslist的值,而是返回一个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. 因此,您可以将结果直接分配给list可以使用list.addAll将结果的所有元素添加到列表中。 Note that add would add the List itself as a new element to the List. 请注意, add会将List本身作为新元素添加到列表中。 So you would end up with a List that contains one element that is a List. 因此,您最终将得到一个List,其中包含一个元素,即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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM