Search code examples
regex

Degrees, Minutes and seconds regex


I need validate with RegEx an sexagecimal value, for example: 24° 12' 55,4" or 32° 24' 15,4".

For now, I have the next RegEx, that matches successful with degrees and minutes:

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

But, when add the seconds validator have problems:

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

I'm new with RegEx, any ideas?


Solution

  • 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.