views:

189

answers:

2

Hi, I have very little experience using regular expressions and I need to parse an angle value expressed as bearings, using regular expressions, example:

"N45°20'15.3"E"

Which represents: 45 degrees, 20 minutes with 15.3 seconds, located at the NE quadrant.

The restrictions are:

  • The first character can be "N" or "S"
  • The last character can be "E" or "W"
  • 0 <= degrees <= 59
  • 0 <= minutes <= 59
  • 0 <= second < 60, this can be ommited.

Python preferably or any other language.

Thanks

+4  A: 

A pattern you could use:

pat = r"^([NS])(\d+)°(\d+)'([\d.]*)\"?([EW])$"

one way to use it:

import re
r = re.compile(pat)
m = r.match(thestring)
if m is None:
  print "%r does not match!" % thestring
else:
  print "%r matches: %s" % (thestring, m.groups())

as you'll notice, upon a match, m.groups() gives you the various parts of thestring matching each parentheses-enclosed "group" in pat -- a letter that's N or S, then one or more digits for the degrees, etc. I imagine that's what you mean by "parsing" here.

Alex Martelli
Thank you very much, that was fast
Eric Acevedo
+8  A: 

Try this regular expression:

^([NS])([0-5]?\d)°([0-5]?\d)'(?:([0-5]?\d)(?:\.\d)?")?([EW])$

It matches any string that …

  • ^([NS])   begins with N or S
  • ([0-5]?\d)°   followed by a degree value, either a single digit between 0 and 9 (\d) or two digits with the first bewteen 0 and 5 ([0-5]) and the second 0 and 9, thus between 0 and 59, followed by °
  • ([0-5]?\d)'   followed by a minutes value (again between 0 and 59) and '
  • (?:([0-5]?\d)(?:\.\d)?")?   optionally followed by a seconds value and " sign, seconds value between 0 and 59 with an optional additional decimal point, and
  • ([EW])$   ends with either E or W.

If you don’t want to allow the values under ten to have preceeding zeros, change the [0-5] to [1-5].

Gumbo
nice -- tighter than mine as it also checks the range of the numbers!
Alex Martelli
Good answer, for sake of "encyclopediness" it's probably worth expanding it a bit about what is what.
Slartibartfast