0

Lets say i have a string like this:

location: Location[gps 39.549497,-120.328997 hAcc=20 et=+44m40s745ms alt=0.0 vel=0.0 bear=0.0 vAcc=??? sAcc=??? bAcc=??? {Bundle[mParcelledData.dataSize=96]}]

I want to extract 39.549497 and -120.328997

i have tried with the below code:

    Pattern p = Pattern.compile("[0-9]+[.][0-9]+");
    Matcher m = p.matcher(logLat);
    while (m.find()) {
        Log.i("found is", m.group());
    }

but could not get the negative number.

  • 1
    Does this answer your question? [Regular expression for floating point numbers](https://stackoverflow.com/questions/12643009/regular-expression-for-floating-point-numbers) – Chayan Bansal Apr 19 '20 at 09:53

1 Answers1

0

Try using the pattern:

Location\[gps (-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)

Your updated Java code:

Pattern p = Pattern.compile("Location\\[gps (-?\\d+(?:\\.\\d+)?),(-?\\d+(?:\\.\\d+)?)");
Matcher m = p.matcher(logLat);
while (m.find()) {
    Log.i("found lat,lng: " + m.group(1) + "," + m.group(2));
}

The general pattern for a floating point number which might be negative is:

-?\d+(?:\.\d+)?

The exact pattern I used above also has context to only target the latitude/longitude values of interest (but not other floating point numbers within the input). See the demo link below.

Demo

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360