Java Split String using regular expression -
i have string
reads parsegeopoint[30.132531,31.312511]
. how can coordinates saved in double
variables. i.e. want have double lat = 30.132531;
, double lang = 31.312511;
here have tried:
string mytext = "parsegeopoint[30.132531,31.312511]"; string [] latlong= mytext.split("["); //it needs escape character string [] latlong2= latlong[1].split(","); double lat = double.parsedouble(latlong2[0]); string[] latlong3= latlong2[1].split("]");//also escape character needed here double lang = double.parsedouble(latlong3[0]);
two things: how split on square bracket given needs escape character? second, feel in way. there must simpler way. it?
how split on square bracket given needs escape character?
i guess mean doesn't compile:
string [] latlong= mytext.split("[");
to make compile, escape [
:
string [] latlong= mytext.split("\\[");
here's way extract doubles string using regular expressions:
pattern pattern = pattern.compile("parsegeopoint\\[([\\d.-]+),([\\d.-]+)]"); matcher matcher = pattern.matcher(mytext); if (matcher.matches()) { lat = double.parsedouble(matcher.group(1)); lang = double.parsedouble(matcher.group(2)); }
another way using substrings:
int bracketstartindex = mytext.indexof('['); int commaindex = mytext.indexof(','); int bracketendindex = mytext.indexof(']'); lat = double.parsedouble(mytext.substring(bracketstartindex + 1, commaindex)); lang = double.parsedouble(mytext.substring(commaindex + 1, bracketendindex));
Comments
Post a Comment