Jack W
Jack W

Reputation: 31

Extract IP and Cordinates from string in Java

Hi I have a Java program which runs and finds my machines longitude and latitude coordinates, it outputs this as a long string show below,

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

What I am trying to do now is to only extract from this string: the IP address and the two coordinates, I have been successful in acquiring the IP address but cant seem to get the two coordinates. The end result would hopefully be

192.168.159.1,52.258301,+-7.111900

So far ive used these expressions to get the IP address

(?:(?: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]?)

Which works just fine and then attempted to get the coordinates using this

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

but it only gets the first coordinate followed by it again

Thanks

Upvotes: 0

Views: 496

Answers (2)

Kent
Kent

Reputation: 195059

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+

Upvotes: 1

sissi_luaty
sissi_luaty

Reputation: 2889

An approach to extract the two coordinates, without regex, can be:

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

Upvotes: 0

Related Questions