0

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. 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

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);
}
user316114
  • 803
  • 7
  • 18

1 Answers1

0

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)