Reputation: 1235
I have the below text format
String s = "
key1:value1;
key2:value2;
key3:value3;
key4:value4;
key5:value5;
key6:https://url1.com, https://url2.com;
key7:value;";
Note: (the number of urls in key6 will be 1 to many and non linear)
I am splitting the s with 7 key-value chunks using S.split(";")
String keyValPair[] = s.split(";");
Output will be
/* keyValPair[0] contains key1:value
keyValPair[1] contains key2:value
keyValPair[2] contains key3:value and
keyValPair[6] contains key6:https://url1.com,https://url2.com;
Now I want to again split key and value separately and store it in arrays 0 and ist position.
//while looping into keyValPair[i]
String[] singleKeyVal[] = keyValPair[0].split(":");
/*Output
singleKeyVal[0] will have Key1
singleKeyVal[1] will have Value1
perform some task and clear the array singlekeyVal[]
The question is how to correctly split the Key6
//while looping into KeyValPair[i]
String[] singleKeyVal[] = keyValPair[5].split(":"); //6th chunk contains : in the URL too
/*Output
singleKeyVal[0] will have Key6
singleKeyVal[1] should contain https://url1.com,https://url2.com
also note that above example contains only 2 urls but it will contain urls between 1 to many urls,
Upvotes: 0
Views: 52
Reputation: 328863
There are two split
methods - the second one takes a limit
argument that allows you to specify the maximum number of groups you want. In your case:
String[] singleKeyVal = keyValPair[5].split(":", 2);
should do what you want.
ps: you should adopt Java naming conventions (variables start in lower case).
Upvotes: 3
Reputation: 11942
There is an overloaded split
that takes a second argument called limit
:
The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array.
So use
String[] SingleKeyVal[] = KeyValPair[5].split(":", 2);
to only split once and get an array with size 2.
Upvotes: 3