Java 使用正则表达式拆分字符串
Java Split String using regular expression
我有 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]);
两件事:
鉴于它需要转义字符,如何在方括号上拆分?
第二,我觉得这样做太过分了。必须有更简单的方法。这是什么?
How to split on the square bracket given that it needs an escape character?
我猜你的意思是这不能编译:
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));
我有 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]);
两件事: 鉴于它需要转义字符,如何在方括号上拆分? 第二,我觉得这样做太过分了。必须有更简单的方法。这是什么?
How to split on the square bracket given that it needs an escape character?
我猜你的意思是这不能编译:
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));