Java Split String使用正则表达式

时间:2015-10-02 22:17:21

标签: java string-parsing

string读取ParseGeoPoint[30.132531,31.312511]。如何获取double变量中保存的坐标。即我想要加倍lat = 30.132531;double lang = 31.312511;

以下是我的尝试:

String myText = "ParseGeoPoint[30.132531,31.312511]";
String [] latlong= myText.split("["); //it needs an escape character
String [] latlong2= latlong[1].split(",");
Double lat = Double.parseDouble(latlong2[0]);
String[] latlong3= latlong2[1].split("]");//also an escape character is needed here
Double lang = Double.parseDouble(latlong3[0]);

两件事: 如果它需要一个转义字符,如何拆分方括号? 其次,我觉得这样做太过分了。必须有更简单的方法。它是什么?

1 个答案:

答案 0 :(得分:2)

  

如果需要转义字符,如何拆分方括号?

我猜你的意思是这不会编译:

String [] latlong= myText.split("[");

要进行编译,请转义[

String [] latlong= myText.split("\\[");

这是另一种使用正则表达式从字符串中提取双精度的方法:

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));
}

另一种方法是使用子串:

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));