如果x!= 0,则不使用0.x.x.x的ipv4地址的正则表达式

时间:2017-11-01 19:54:08

标签: python regex

我正在为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

2 个答案:

答案 0 :(得分:1)

我认为你要找的正则表达式是:

<Router> <ResponsiveDrawer> <div className="App"> <div> <Route exact path="/" component={Administrator} /> <Route path="/admin" component={Administrator} /> <Route exact path="/jobs" component={Jobs} /> <Route path="/jobs/:id" render={({match}) => <ViewJob id={match.params.id} />} /> <Route path="/reports" component={Reports} /> </div> </div> </ResponsiveDrawer> </Router>

您可以对其进行测试here

答案 1 :(得分:1)

以下是符合要求的正则表达式:

^(?!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+ zeros
    • (?:\.0*[1-9][0-9]*){3} - 连续3次出现
    • \. - 一个点
    • 0* - 0+ zeros
    • [1-9] - 从19
    • 的数字
    • [0-9]* - 任意0+位数
    • $ - 字符串结束。

此外,八位位组正则表达式现在也匹配0

  • (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
    • 25[0-5]| - 250255
    • 2[0-4][0-9]| - 200249
    • [01]?[0-9][0-9]? - 10(可选,1或0次),然后是任意数字,然后是任意1位或0位数(可选数字)。

A 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!