Degrees, minutes and seconds

I need to check with RegEx by gender, for example: 24 Β° 12 '55, 4 "or 32 Β° 24 '15.4".

Now I have the following RegEx that matches success with degrees and minutes:

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

But when adding a stopwatch, the validator has 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 to RegEx, any ideas?

+7
regex
source share
1 answer

First, you have redundancy:

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

It can become simple:

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

Then you have a logical problem, in the second match you match 0-4, then 0-9 (ie 00-49), and then match only 59. You can change this to:

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

for matching 00-59

Next, look at your second modification:

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

Same problem as before, except that now you have added the decimal, but not both sides | therefore, it will correspond only on one side, if we fix it, as we fixed the last one, which we get:

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

Then you have two single quotes instead of double quotes, so fix this:

 ^([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 mandatory? Probably no. So mark this as potentially missing using ?

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

Further, is the second part of the second mandatory? Probably not, so mark this as potentially missing:

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

Finally, I assume that each part, with the exception of 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])?")?$ 

Other things you can do to make it better. But that should get you started.

+9
source share

All Articles