arrays - Split string with only first instance java -
i have below response telnet server
string response = "i:barco@noiclt22815||k:cms||o:regetperspectivelist||a0:googlep||a1:yahoop||a2:gmail||a3:test||a4:hello||a16:cctv barco||a17:cctv: corridor cc||a18:cctv: dr andy warhol||a19:cctv: dr gaudi (analog)||a20:cctv: dr miro||a21:cctv: entrance cc||a22:cctv: gaudi demo room megapixel||";
i want attributes value e.g a0, a1 etc , therefore write below logic
string[] strings = response.split("[||]"); list<string> list = new arraylist<>(); (string string : strings) { if (string.contains(":")) { string[] attributes = string.split(":"); if (attributes[0].startswith("a")) { list.add(attributes[1]); } } }
but problem string.split(":") split gives me string array requires 2 length size string array only. e.g. response a17 attribute gives me "cctv" attributes[1] , "corridor cc" attributes[2] requires "cctv: corridor cc" attribute [1] only.
what regular expression should write in string.split(regexp) string can split based on first instance of colon operator 2 length size string array.
the code below splits on pipes first, , then uses regex extract out properties , attributes. note there, away doing split.
string response = "i:barco@noiclt22815||k:cms||o:regetperspectivelist||a0:googlep||a1:yahoop||a2:gmail||a3:test||a4:hello||a16:cctv barco||a17:cctv: corridor cc||a18:cctv: dr andy warhol||a19:cctv: dr gaudi (analog)||a20:cctv: dr miro||a21:cctv: entrance cc||a22:cctv: gaudi demo room megapixel||"; string[] metaparts = response.split("\\|\\|"); (int i=0; < metaparts.length; ++i) { string property = metaparts[i].replaceall("(.*):(.*)", "$1"); string attribute = metaparts[i].replaceall("(.*):(.*)", "$2"); system.out.println(property + ":" + attribute); }
as others here have said, regular expressions not panacea cure development problems. , splitting doing heavy lifting problem.
Comments
Post a Comment