简体   繁体   English

JAVA:解析单个字符串键值对

[英]JAVA: Parsing single String key value pairs

I'm trying to figure out a way to separate out key value pairs that are on the same line. 我正在尝试找出一种方法来分离同一行上的键值对。

Take the following input as a sample 将以下输入作为示例

key1=0 key2=val0 key3=my val 0 key4=some (val)

At first, I didn't see this in my input data because it was buried and didn't think there were any spaces. 刚开始,我在输入数据中看不到它,因为它被掩埋了,并且认为没有任何空格。 As such I separated each row into an array based on the space and then read the resulting array as a Properties object and finally into my Map. 这样,我根据空间将每一行分成一个数组,然后将所得的数组作为Properties对象读取,最后读取到Map中。 This is now producing bad results. 现在这产生了不好的结果。

At this point I think this is a problem for regex, and I am notoriously awful with that skill. 在这一点上,我认为这对正则表达式来说是个问题,而众所周知,我对这种技巧并不满意。

Is there a way to take the above sample data (single string) and correctly parse it into the resulting HashMap 有没有办法获取上述示例数据(单个字符串)并将其正确解析为生成的HashMap

key1:0
key2:val0
key3:my val 0
key4:some (val)

tiya! 蒂雅!

Edit, answer: 编辑,回答:

Pattern p = Pattern.compile("(\\w+)=\"*((?<=\")[^\"]+(?=\")|([^\\s]+))\"*");

String test = "a0=d235 a1=2314 com1=\"abcd\" com2=\"a b c d\"";
Matcher m = p.matcher(test);

while(m.find()){
    print m.group(1);
    print "="
    println m.group(2);
}

Try this. 尝试这个。

String s = "key1=0 key2=val0 key3=my val 0 key4=some (val)";
Pattern pat = Pattern.compile("(\\b\\w+)=(.*?)(?=\\w+=|$)");
Matcher m = pat.matcher(s);
while (m.find())
    System.out.println(m.group(1) + ":" + m.group(2));

result 结果

key1:0 
key2:val0 
key3:my val 0 
key4:some (val)

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

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