繁体   English   中英

尝试使用 Python 从文件中提取所有 IP 地址

[英]Trying to extract all IP addresses from a file using Python

菜鸟在这里。

我正在尝试从一个文件中提取所有 IP 地址,其中 IP 地址都位于随机位置,有时一行中有多个 IP。 这是一个文本文件,其内容如下所示:

hello9.9.9.9                     hdi3ohdoi3hoi3oid2         10.3.2.3            2.3.4.5
ddjeijfdeio
eifhoehjwiehfiowe
uiewhduihewiudhue
8.8.8.8, 20.20.20.20
de2hd9j39ud9829d8 192.168.10.24

我的代码只返回每行的第一个 ip 地址,

['9.9.9.9', '8.8.8.8', '192.168.10.24']

我的代码如下:


with open('C:/testfile.txt') as fh:
    file = fh.readlines()

pattern = re.compile(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})')

lst = []

for line in file:
    match = pattern.search(line)
    if match is not None:
        lst.append(match[0])

print(lst)

有什么想法可以列出所有IP吗?

提前致谢

Ĵ

您可以使用re.findall

import re

data = """
hello9.9.9.9                     hdi3ohdoi3hoi3oid2         10.3.2.3            2.3.4.5
ddjeijfdeio
eifhoehjwiehfiowe
uiewhduihewiudhue
8.8.8.8, 20.20.20.20
de2hd9j39ud9829d8 192.168.10.24
"""

result = re.findall(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', data)
print(result)

结果:

['9.9.9.9', '10.3.2.3', '2.3.4.5', '8.8.8.8', '20.20.20.20', '192.168.10.24']

使用pattern.findall()查找所有出现。 否则它将找到第一次出现。

import re

with open('testfile.txt') as fh:
    file = fh.readlines()

pattern = re.compile(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})')

lst = []
for line in file:
    match = pattern.findall(line)
    if len(match) != 0:
        lst.extend(match)
print(lst)

output:

['9.9.9.9', '10.3.2.3', '2.3.4.5', '8.8.8.8','20.20.20.20','192.168.10.24']

pattern.search function 只搜索第一次出现,

所以我建议使用findall方法而不是 search 方法,这样您的代码可能如下所示:


with open('C:/testfile.txt') as fh:
    file = fh.readlines()

pattern = re.compile(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})')

lst = []

for line in file:
    match = re.findall(pattern,text)
    #match = pattern.findall(line)#searching for first one
    if match is not None:
        for x in match:#iter and add
            lst.append(x)
    #or 
        #lst.extend(match)#adds a list to the list

print(lst)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM