度、分和秒正则表达式 [英] Degrees, Minutes and seconds regex

查看:25
本文介绍了度、分和秒正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 RegEx 验证十六进制值,例如:24° 12' 55,4" 或 32° 24' 15,4".

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])''$

我是 RegEx 的新手,有什么想法吗?

I'm new with RegEx, any ideas?

推荐答案

首先,你有一些冗余:

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

可以变成:

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

接下来,您遇到了一个逻辑问题,在您的第二场比赛中,您先匹配 0-4,然后匹配 0-9(即 00-49),然后只匹配 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]'$

匹配 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.

这篇关于度、分和秒正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆