我有以下文字格式
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)
我使用S.split(“;”)将7个键值块拆分为s
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;
现在我想再次分开键和值并将其存储在数组0和ist位置。
//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[]
问题是如何正确拆分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,
答案 0 :(得分:3)
an overloaded split
有一个名为limit
的第二个参数:
limit参数控制模式的应用次数,因此会影响结果数组的长度。
所以使用
String[] SingleKeyVal[] = KeyValPair[5].split(":", 2);
只拆分一次,得到一个大小为2的数组。
答案 1 :(得分:3)
有两种split
方法 - the second one 采用limit
参数,允许您指定所需的最大组数。在你的情况下:
String[] singleKeyVal = keyValPair[5].split(":", 2);
应该做你想做的事。
ps:你应该采用Java命名约定(变量以小写字母开头)。