gpt4 book ai didi

Java 使用正则表达式拆分字符串

转载 作者:行者123 更新时间:2023-11-30 08:46:19 25 4
gpt4 key购买 nike

我有 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("\\[");

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

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

关于Java 使用正则表达式拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32916649/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com