我正在为 ipv4 地址做一个正则表达式,非常有趣的是 Ubuntu 和一些 RFC 引用文献指出 0.x.x.x 如果 x != 0 被保留,所以无效。对此更优化的正则表达式应该是什么?我有这个:
import re
matcher = re.compile(r'^(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]|[1-9])(\.(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9])){3}\Z^(0)(.0){3}\Z')
例如:
0.1.2.3 => should be invalid
1.0.0.0 => should be valid
0.0.0.0 => should be valid
最佳答案
这是满足要求的正则表达式:
^(?!0+(?:\.0*[1-9][0-9]*){3}$)(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$
参见its online demo .
要点是:
(?!0+(?:\.0*[1-9][0-9]*){3}$)
- 一个(?!... )
是一个否定的前瞻,如果其模式匹配,则匹配失败:0+
- 1+ 个零(?:\.0*[1-9][0-9]*){3}
- 连续出现 3 次\.
- 一个点0*
- 0+ 个零[1-9]
- 从1
到9
的数字[0-9]*
- 任意 0+ 位数字$
- 字符串结尾。
此外,八位字节正则表达式现在也匹配 0
:
(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
:25[0-5]|
-250
直到255
2[0-4][0-9]|
-200
直到249
[01]?[0-9][0-9]?
-1
或0
(可选,1 次或 0 次) 然后任意数字,然后任意 1 或 0 数字(可选数字)。
一个Python demo :
import re
rx = """(?x)^ # start of string
(?! # start of the negative lookahead that fails the match if
0+(?:\.0*[1-9][0-9]*){3}$ # 0s appear only in the first octet
) # end of the lookahead
(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) # First octet regex
(?: # start of the non-capturing group
\. # a dot
(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) # octet
){3} # repeated 3 times
$ # end of string
"""
lst = ['0.1.2.3','1.0.0.0','0.0.0.0']
for s in lst:
m = re.match(rx, s)
if m:
print("{} matched!".format(s))
else:
print("{} did not match!".format(s))
输出:
0.1.2.3 did not match!
1.0.0.0 matched!
0.0.0.0 matched!
关于python - 如果 x != 0,则不带 0.x.x.x 的 ipv4 地址的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47062663/