gpt4 book ai didi

java - 如何分割所需格式的字符串?

转载 作者:行者123 更新时间:2023-12-01 07:47:48 26 4
gpt4 key购买 nike

我有以下文本格式

 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(";") 将 s 拆分为 7 个键值 block

 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,

最佳答案

有两种 split 方法 - the second one 采用 limit 参数,允许您指定所需的最大组数。对于您的情况:

String[] singleKeyVal = keyValPair[5].split(":", 2);

应该做你想做的事。

ps:您应该采用Java命名约定(变量以小写开头)。

关于java - 如何分割所需格式的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47205600/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com