首页 > 解决方案 > 正则表达式验证自定义格式

问题描述

我有这种格式:xx:xx:xx或者xx:xx:xx-y,其中 x 可以是 0-9 af AF,而 y 只能是 0 或 1。

我想出了这个正则表达式:([0-9A-Fa-f]{2}[:][0-9A-Fa-f]{2}[:][0-9A-Fa-f]{2}|[-][0-1]{1})

(见正则表达式)。

但这0a:0b:0c-3也匹配,这是意料之外的。

有没有办法从结果中删除这些案例?

标签: javaregex

解决方案


[:]表示列表中仅包含 的字符:。它与 相同 :。相同[-]的结果与 相同-
此外,{1}意思是“前一段正好一次”。它没有任何影响,您可以完全删除它。

要匹配xx:xx:xxor xx:xx:xx-y,匹配的部分-y必须是可选的。可选部分后面的量词?将其标记为可选。

总而言之,你regex应该是这样的:

[0-9A-Fa-f]{2}:[0-9A-Fa-f]{2}:[0-9A-Fa-f]{2}(-[01])?

如果regex可以告诉您使用的引擎忽略字符大小写,那么您可以从所有字符类中删除A-F(或),然后变为:a-fregex

[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}(-[01])?

它是如何工作的,一点一点:

[0-9a-f]      # any digit or letter from (and including) 'a' to 'f'
{2}           # the previous piece exactly 2 times
:             # the character ':'
[0-9a-f]
{2}
:
[0-9a-f]
{2}
(             # start a group; it does not match anything
  -           # the character '-'
  [01]        # any character from the class (i.e. '0' or '1')
)             # end of group; the group is needed for the next quantifier
?             # the previous piece (i.e. the group) is optional
              # it can appear zero or one times

在行动中看到它:https ://regexr.com/4rfvr

更新

正如@the-fourth-bird 在评论中提到的那样,如果regex必须匹配整个字符串,那么您需要锚定其末端:

^[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}(-[01])?$

^因为 a 的第一个字符regex匹配字符串的开头,$因为最后一个字符匹配字符串的结尾。这样,仅匹配整个字符串(当or部分regex之前或之后没有其他字符时)。xx:xx:xxxx:xx:xx-y

如果您使用regex来查找xx:xx:xxxx:xx:xx-y在更大的字符串中,则无需添加^and $。当然,您可以只在字符串的开头或结尾添加^$让匹配。regex


推荐阅读