How to parse angular values ​​using regular expressions

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

"N45 ° 20'15.3" E "

What it is: 45 degrees, 20 minutes with 15.3 seconds located in the NE quadrant.

Limitations:

  • 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 may be limited.

Python is preferable or any other language.

thanks

+3
source share
2

:

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

, ...

  • ^([NS]) N S
  • ([0-5]?\d)°, , 0 9 (\d), 0 5 ([0-5]) 0 9, , 0 59, °
  • ([0-5]?\d)', ( 0 59) '
  • (?:([0-5]?\d)(?:\.\d)?")?, ", 0 59
  • ([EW])$ E, W.

, , [0-5] [1-5].

+8

, :

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

:

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())

, m.groups() thestring, , , pat - N S, .. , "" .

+4

Source: https://habr.com/ru/post/1709483/


All Articles