将字符串拆分为键值对,其中值可以包含分隔符
我试图将一个字符串拆分为键值对,这非常简单,但我很晚才意识到我的输入没有任何验证。该字符串可以包含与我用来分割的相同的分隔符。不确定这是否可行,但有人可以帮助找到一种方法将此字符串拆分为有效的键/值对吗?
当前逻辑:
String key = "key1=value1,key2=value2,key3=value3,with,delimeter"
Map<String, String> map = new HashMap<>();
String[] entries = key.split(",");
for(String entry : entries) {
String[] keyValue = entry.split("=");
map.put(keyValue[0], keyValue[1]);
}
预期输出:
key1:value1
key2:value2
key3:value3,with,delimeter
但是此代码会导致 java.lang.ArrayIndexOutOfBoundsException
因为最后一个值中有逗号。
注意:我无法将 , 转换为不同的分隔符,因为我需要按原样处理字符串并且它可以包含任何字符。
I am trying to split a string into key-value pairs which is very straight forward, but I realized very late that I don't have any validation on my input. the string can contain same delimiter that I am using to split. Not sure if this is possible but can someone please help find a way to split this string into a valid key/value pairs?
The current logic:
String key = "key1=value1,key2=value2,key3=value3,with,delimeter"
Map<String, String> map = new HashMap<>();
String[] entries = key.split(",");
for(String entry : entries) {
String[] keyValue = entry.split("=");
map.put(keyValue[0], keyValue[1]);
}
Expected output:
key1:value1
key2:value2
key3:value3,with,delimeter
But this code causes java.lang.ArrayIndexOutOfBoundsException
as there are comma in the last value.
Note: I cannot convert , into a different delimiter as I need to process the string as-is and it can container any character.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么不用
=
分割它,并将字符串放在最后一个,
之后价值?
结果:
注意:仅当键不包含逗号时才有效。
Why not split it with
=
, and make the string after the last,
the value?
Result:
Note: It only works if the key does not contains commas.