python重新匹配ip地址

python re match ip address

我有通过 ip 地址合并的简单脚本。我想从以下输出中对 ip 进行正则表达式

Starting Nmap 7.91 ( https://nmap.org ) at 2020-12-11 15:04 EST
Nmap scan report for host.com (127.0.0.1)
Host is up (0.14s latency).

我试过使用这个工具:https://pythex.org/。我能够与以下模式匹配

(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})

但是此代码 returns 0 匹配

regex = re.match("(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})",output)
print(regex)

预期的输出应该是 127.0.0.1。如有任何帮助,我们将不胜感激。

re.match matches a pattern at the beginning of the given string. It looks like what you want is re.findall or re.search:

output = '''
Starting Nmap 7.91 ( https://nmap.org ) at 2020-12-11 15:04 EST
Nmap scan report for host.com (127.0.0.1)
Host is up (0.14s latency).'''

regex = re.findall("(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})", output)

print(regex) # ['127.0.0.1']

你应该使用re.search

>>> import re
>>> text = 'Nmap scan report for host.com (127.0.0.1)'
>>> re.search(r"(?:[0-9]{1,3}\.){3}[0-9]{1,3}", text).group()
'127.0.0.1'

与re.match您可以按如下方式使用它:

output = 'Your output'
ip = re.match(r'\(([\d\.]*)\)').groups()[0]

解释:re.match 将 return 一个 class ,它被方括号括起来并带有“.”和数字而已。然后 groups() 将 return 所有匹配的组。 index[0] 处的字符串将是它的匹配项。