Featured post
Java:how to group similar strings (items) to respective array (group)? -
i have following string "0#aitem, 0#aitem2, 0#aitem3, 1#bitem, 1#bitem2, 2#citem, nitem, nitem2".
the 0# shows group number. aitem, aitem2, aitem3 belong group 0. bitem, bitem2 in group 1. citem in group 2. if there no group number, place in separate group. nitem, nitem2 placed in group 3.
i create array each group, , place "items" in respective group(array). end like
[array("aitem,aitem2,aitem3"), array("bitem, bitem2"), array("citem"), array("nitem, nitem2")] i guessing need arraylist hold groups (arrays) respectively has appropriate elements (items).
this started don't know if best approach. string dynamic, there can number of groups , has follow criteria above.
string[] x = pattern.compile(",").split("0#item, 0#item2, 0#item3, 1#item, 1#item2, 2#item, item"); (int ii=0; ii<x.length; ii++) { system.out.println(i + " \"" + x[ii] + "\""); }
my answer shows how can use single regex extract both group , item. can store these in map.
string s = "0#aitem, 0#aitem2, 0#aitem3, 1#bitem, 1#bitem2, 2#citem, nitem, nitem2"; pattern p = pattern.compile("(\\d*)[#]{0,1}(\\w+?)(,|$)"); matcher m = p.matcher(s); map<string, list<string>> map = new treemap<string, list<string>>(); while(m.find()){ string group = m.group(1); string item = m.group(2); list<string> items = map.get(group); if(items == null){ items = new arraylist<string>(); map.put(group, items); } items.add(item); } //let's print out for(string key : map.keyset()){ system.out.println(key + " : " + map.get(key)); } prints:
: [nitem, nitem2] 0 : [aitem, aitem2, aitem3] 1 : [bitem, bitem2] 2 : [citem] at moment, items no group keyed against empty string. i'll leave @ exercise handle scenario. should case of finding max key , incrementing it.
i'm sure regex can improved written in haste.
- Get link
- X
- Other Apps
Comments
Post a Comment