0

I've been trying to extract part of a string. I'm doing it in an Android App (Java).

My problem is that I'll have a string that starts out like this:

Location[fused 20.01234,-30.9876 acc=20 (...)

That represents the device's current coordinates (I made up 20 and -30 there) and some other measurements. I want to extract the 2 coordinates from that string (they'll always be in between "fused " and " acc"), and store them as floats.

I've looked around and concluded that probably RegExs are needed to solve this, but keep in mind I've only used Regular Expressions once before, and I'm still very inexperienced with them.

Any guidance on how to go about solving this will be greatly appreciated!

2
  • use String.split() tutorialspoint.com/java/java_string_split.htm Commented Feb 14, 2017 at 3:29
  • 1
    if there is always a space before and after coordinators, then you can get both the coordinators without RegEx use. String location = "Location[fused 20.01234,-30.9876 acc=20"; location = location.substring(location.indexOf(" "), location.lastIndexOf(" ")); String locationArr[]= location.split(","); System.out.println("lat : "+locationArr[0]); System.out.println("long: " + locationArr[1]); Commented Feb 14, 2017 at 3:49

1 Answer 1

1

RegExr is a great site for learning and building regex: http://regexr.com/

Matching your string with this regex will give you the 2 coordinates:

fused\s(-?\d+\.\d+),(-?\d+\.\d+)\s

Copy this expression to RegExr to see what each of these character means.

To use regex expression in Java, you'll need to make sure you escape the backslash characters (add an extra backslash)

In Java:

public static void main(String[] args) {
    String yourString = "Location[fused 20.01234,-30.9876 acc=20 ";

    Pattern pattern = Pattern.compile("fused\\s(-?\\d+\\.\\d+),(-?\\d+\\.\\d+)\\s");
    Matcher matcher = pattern.matcher(yourString);
    if(matcher.find()) {
        String coordinate1 = matcher.group(1);
        String coordinate2 = matcher.group(2);
        System.out.println(coordinate1);
        System.out.println(coordinate2);
    }
}

Output:

20.01234
-30.9876
Sign up to request clarification or add additional context in comments.

1 Comment

It works perfectly! And thank you for the tip, I didn't know about that site. It looks very useful for practicing Regexs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.