views:

632

answers:

3

Anyone have a regex to strip lat/long from a string? such as:

ID: 39.825 -86.88333

+7  A: 

To match one value

-?\d+\.\d+

For both values:

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

And if the string always has this form:

"ID: 39.825 -86.88333".match(/^ID:\ (-?\d+\.\d+)\ (-?\d+\.\d+)$/)
Gumbo
better answer, covers grouping! maybe re-accept this one.
Andreas Petersson
+2  A: 
var latlong = 'ID: 39.825 -86.88333';

var point = latlong.match( /-?\d+\.\d+/g );

//result: point = ['39.825', '-86.88333'];
meouw
@Detroitpro - make sure to add a -? in front of the first \d to get negative values as well.
Sean Bright
I've edited my answer to include Sean's absolutely correct suggestion
meouw
+2  A: 
function parseLatLong(str) {
    var exp = /ID:\s([-+]?\d+\.\d+)\s+([-+]?\d+\.\d+)/;

    return { lat: str.replace(exp, "$1"), long: str.replace(exp, "$2") };          
}

function doSomething() {
    var res = parseLatLong("ID: 39.825 -86.88333");

    alert('Latitude is ' + res.lat + ", Longitude is " + res.long);
}
Sean Bright