【问题标题】:REGEX and IP Addresses正则表达式和 IP 地址
【发布时间】:2015-11-22 08:13:49
【问题描述】:

Exscript any_match() 函数使用正则表达式匹配字符串中的模式并以元组的形式返回结果。

我正在尝试匹配跟踪路由输出中的 IP 地址。它在大多数情况下都有效,但由于某种原因会返回一些额外的值(除了目标地址之外)。我希望在正确的正则表达式中得到一些帮助,以仅返回 IP 地址而不返回额外的值。 **注意:**我已经在 stackoverflow 上搜索并搜索了正则表达式模式,并研究了正则表达式帮助页面。这是迄今为止最接近的正则表达式。

def ios_commands(job, host, conn):        
conn.execute('terminal length 0')
conn.execute('tr {}'.format(DesAddr))
print('The results of the traceroute', repr(conn.response))
for hops in any_match(conn,r'(([0-9]{1,3}\.){3}[0-9]{1,3})'):
    hop_addresses = list(hops)

输出

正在搜索的字符串

hostname>('The results of the traceroute', "'tr 192.33.12.4\\r\\nType escape sequence to abort.\\r\\nTracing the route to hostname (192.33.12.4)\\r\\nVRF info: (vrf in name/id, vrf out name/id)\\r\\n  1 hostname (192.32.0.174) 0 msec 0 msec 0 msec\\r\\n  2 hostname (192.32.0.190) 0 msec 0 msec 0 msec\\r\\n  3 192.33.226.225 [MPLS: Label 55 Exp 0] 0 msec 4 msec 0 msec\\r\\n  4 192.33.226.237 0 msec 0 msec 0 msec\\r\\n  5 hostname (192.33.12.4) 4 msec *  0 msec\\r\\nhostname>'")

['192.33.12.4', '12.'] #note the extra '12.' value

['192.33.12.4', '12.']

['192.32.0.174', '0.']

['192.32.0.190', '0.']

['192.33.226.225', '226.']

['192.33.226.237', '226.']

['192.33.12.4', '12.']

【问题讨论】:

    标签: regex python-2.7 ip-address


    【解决方案1】:

    您的模式中有 2 个匹配的组。第一个(和外部的)用于整个 IP 地址;第二组重复三次:

    ([0-9]{1,3}\.){3}
    

    使用非捕获组:

    ((?:[0-9]{1,3}\.){3}[0-9]{1,3})
    

    【讨论】:

      猜你喜欢
      • 2011-06-20
      • 2017-03-15
      • 1970-01-01
      • 2013-02-21
      • 1970-01-01
      • 2012-04-17
      相关资源
      最近更新 更多