java - Regular expression matching issue with the following scenario -
java - Regular expression matching issue with the following scenario -
i developing application. user come in of setting value in server. when inquire value server through inbuilt api. getting values whole string: example-
name={abc};display={xyz};addressname={123}
here properties name, display , address , there respective values abc, xyz , 123. used split ; first delimeter , = sec dleimeter.
string[] propertyvalues=ipropertiesstrings.split(";"); for(int i=0;i<propertyvalues.length;i++) { if(isnullempty(propertyvalues[i])) continue; string[] propertyvalue=propertyvalues[i].split("="); if(propertyvalue.length!=2) mpropertyvalues.put(propertyvalue[0], ""); else mpropertyvalues.put(propertyvalue[0], propertyvalue[1]); } }
here mpropertyvalues hash map used keeping property name , value.
problem there can string :
case 1: name={abc};display={ xyz=deno; demo2=pol };addressname={123} case 2: name=;display={ xyz=deno; demo2=pol };addressname={123}
i want hashmap filled :
case 1:
name ="abc" display = "xyz= demo; demo2 =pol" addressname = "123"
for case 2:
name ="" display = "xyz= demo; demo2 =pol" addressname = "123"
i looking regular look split these strings;
assuming there can't nested {}
should need
string info = "name=;display={ xyz=deno; demo2=pol };addressname={123}"; pattern p = pattern.compile("(?<name>\\w+)=(\\{(?<value>[^}]*)\\})?(;|$)"); matcher m = p.matcher(data); while (m.find()){ system.out.println(m.group("name")+"->"+(m.group("value")==null?"":m.group("value").trim())); }
output:
name-> display->xyz=deno; demo2=pol addressname->123
explanation
(?<name>\\w+)=(\\{(?<value>[^}]*)\\})?(;|$)
can split parts
(?<name>\\w+)=
represents xxxx= , place xxxx
in grouping named name
(of property) (\\{(?<value>[^}]*)\\})?
optional {xxxx}
part x
can't }
. place xxxx
part in grouping named value
. (;|$)
represents ;
or end of info (represented $
anchor) since formula name=value;
or in case of pair placed @ end of info name=value
. java regex
Comments
Post a Comment