0

嗨,我有一个 Java 程序,它运行并查找我的机器的经度和纬度坐标,它将其输出为如下所示的长字符串,

htt://maps.google.com/maps?q=52.258301,+-7.111900+(192.168.159.1Country:Ireland,City:Waterford-by htt://www.javaquery.com)&iwloc=A&hl=en

我现在要做的是只从这个字符串中提取:IP地址和两个坐标,我已经成功获取了IP地址但似乎无法获得这两个坐标。最终结果希望是

192.168.159.1,52.258301,+-7.111900

到目前为止,我使用这些表达式来获取 IP 地址

(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)

哪个工作得很好,然后尝试使用它来获取坐标

[0-9]+(\\.[0-9][0-9]?)?

但它只获得第一个坐标,然后再次

谢谢

4

2 回答 2

1

try with this regex:

"(?<=\\?q=)([^(]*)\\(([\\d.]*)"

group(1) is 52.258301,+-7.111900+

group(2) is the ip

EDIT add codes for the regex matching/extraction

String regex = "(?<=\\?q=)([^(]*)\\(([\\d.]*)";
        String s = "htt://maps.google.com/maps?q=52.258301,+-7.111900+(192.168.159.1Country:Ireland,City:Waterford-by htt://www.javaquery.com)&iwloc=A&hl=en";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(s);
        if (m.find()) {
            System.out.println(m.group(2));
            System.out.println(m.group(1));
        }

outputs:

192.168.159.1
52.258301,+-7.111900+
于 2013-03-05T14:53:04.420 回答
0

无需正则表达式即可提取两个坐标的方法可以是:

String str="http://maps.google.com/maps?q=52.258301,+-7.111900+(192.168.159.1Country:Ireland,City:Waterford-by htt://www.javaquery.com)&iwloc=A&hl=en";

int index_x=str.indexOf("?q=")+"?q=".length();
int index_x_end=str.indexOf(",");
int index_y=index_x_end+",".length();
int index_y_end=str.indexOf("+(");

System.out.println(str.substring(index_x, index_x_end));    //prints 52.258301
System.out.println(str.substring(index_y, index_y_end));    //prints +-7.111900
于 2013-03-05T14:59:54.163 回答