【问题标题】:Python regex extract IPs separated with colon [duplicate]Python正则表达式提取IP用冒号分隔[重复]
【发布时间】:2016-03-27 06:37:40
【问题描述】:

这里是一个例子:'192.168.1.1;192.168.1.2'

我的代码:

import re
regex = '^((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)[;]?)+$'
r = re.match(regex, '192.168.1.1;192.168.1.2')
r.groups() # => ('192.168.1.2',)
# My expected result => ('192.168.1.1', '192.168.1.2',)

# re.findall(regex, '192.168.1.1;192.168.1.2') => ['192.168.1.2'] is not what I want......

我使用()捕获每个IP,但结果只显示一个IP。 是不是我的用法不对?

感谢您的帮助。

【问题讨论】:

标签: python regex


【解决方案1】:

只需使用re.finditer()

import re
regex = '^((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)[;]?)+$'
for r in re.finditer(regex, '192.168.1.1;192.168.1.2'):
  print r.group()

如果你愿意,你也可以使用这个正则表达式: regex = r'(\d{3}\.\d{3}\.\d\.\d)'

【讨论】:

  • 这里只显示192.168.11.1;192.168.12.1,但是我想把这两个ip提取到一个列表中。
  • 使用我提供的正则表达式,然后将其附加到列表中。
  • 哦...,你的意思是regex = r'(\d{3}\.\d{3}\.\d\.\d)'?我觉得这种格式不是我想要的。
猜你喜欢
  • 2022-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多