Degrees, Minutes and seconds regex

First off, you have some redundancy:

^([0-8][0-9]|[9][0])°\s([0-4][0-9]|[5][9])'$

can become just:

^([0-8][0-9]|90)°\s([0-4][0-9]|59)'$

Next you have a logical issue, in your second match, you're matching 0-4 then 0-9 (ie 00-49) and then matching just 59. You can change this to:

^([0-8][0-9]|90)°\s[0-5][0-9]'$

to match 00-59

Next let's look at your seconds modification:

\s([0-4][0-9]|[5][9],[0-9])''$

Same issue as before, except now you've added a decimal, but not to both sides of the | so it will only match on one side, if we fix this like we fixed the last one we get:

^([0-8][0-9]|90)°\s[0-5][0-9]'\s[0-5][0-9],[0-9]''$

Next you have two single quotes instead of a double quote, so fix that:

^([0-8][0-9]|90)°\s([0-5][0-9])'\s[0-5][0-9],[0-9]"$

Now we need to ask ourselves, is the first digit on this mandatory? Probably not. So mark it as potentially missing using a ?

^([0-8]?[0-9]|90)°\s[0-5]?[0-9]'\s[0-5]?[0-9],[0-9]"$

Next, is the fractional part of the second mandatory? Probably not, so mark it as potentially missing:

^([0-8]?[0-9]|90)°\s[0-5]?[0-9]'\s[0-5]?[0-9](,[0-9])?"$

Finally, I'm assuming that each part except for the degrees is not required, mark them as potentially missing:

^([0-8]?[0-9]|90)°(\s[0-5]?[0-9]')?(\s[0-5]?[0-9](,[0-9])?")?$

There's other things you can do to make this better. But, this should get you started.

Tags:

Regex