java - 正则表达式验证自定义格式
问题描述
我有这种格式: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
也匹配,这是意料之外的。
有没有办法从结果中删除这些案例?
解决方案
[:]
表示列表中仅包含 的字符:
。它与 相同
:
。相同[-]
的结果与 相同-
。
此外,{1}
意思是“前一段正好一次”。它没有任何影响,您可以完全删除它。
要匹配xx:xx:xx
or 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-f
regex
[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:xx
xx:xx:xx-y
如果您使用regex
来查找xx:xx:xx
或xx:xx:xx-y
在更大的字符串中,则无需添加^
and $
。当然,您可以只在字符串的开头或结尾添加^
或$
让匹配。regex
推荐阅读
- ios - 如何在 ios 中创建客户端库以与 Turn Server 通信?
- php - 上传多个图像时,获取数据库中的文件夹名称
- java - 从 C++ 调用 Java 方法
- reactjs - 如何在 React JS 中使用 D3 在 Force-Directed Graph 中同一组的节点周围创建一个凸包?
- haskell - 如何使用 Haskell 访问树节点的数值
- python - 嵌套循环使用正则表达式 python
- javascript - 为嵌套的 if 条件反应条件渲染
- asp.net-core - 如何检测用户下载结果
- ajax - select2 ajax 加载数据在部分视图 ASP .NET MVC 中不起作用
- flutter - AnimatedList 中的滑块值错误