i have string in java like:
string whatihavetomatch = "$item1$={key1=1,key2=2,key3=3,}"+ "$item2$={key10=4,key11=5,key3=4,key9=7,}"+ "$itemn$={keyi-1=5,keyi=3,}";
how can define pattern every groups each of them contains item , every key/value associated?
update:
i have build hashmap<string,hashmap<string,integer>>
in every entrykey of external hashmap identifier of item, , returns map of internal "key"/"value".
the "keys"(in example: key1,key2,key3...) don't have specific form, can alphanumerical happens.
this job regular expressions:
string string = "$item1$={key1=1,key2=2,key3=3,}"+ "$item2$={key10=4,key11=5,key3=4,key9=7,}"+ "$itemn$={keyi-1=5,keyi=3,}"; hashmap<string,hashmap<string,integer>> mymap = new hashmap<string,hashmap<string,integer>>(); pattern itempattern = pattern.compile("([^\\s{}]+)=\\{([^{}]+)\\}"); matcher itemmatcher = itempattern.matcher(string); while(itemmatcher.find()) { hashmap<string,integer> item = new hashmap<string,integer>(); string itemname = itemmatcher.group(1); string itemcontent = itemmatcher.group(2); pattern kvpattern = pattern.compile("([^=,]+)=([^=,]+)"); matcher kvmatcher = kvpattern.matcher(itemcontent); while(kvmatcher.find()) { item.put(kvmatcher.group(1), integer.parseint(kvmatcher.group(2))); } mymap.put(itemname, item); } system.out.println(mymap.tostring());
but careful. kimbert said, regexps not right tool kind of work.
Comments
Post a Comment