繁体   English   中英

使用正则表达式模块和.group() 对匹配值进行分组

[英]Grouping the matched values using regex module and .group()

我的文本文件“reg1.txt”如下所示:

Python trainings going on well We are connecting to server having IP 192.168.101.124 for Python hands-on My email id is john1@xyz.com use this email for official purpose. Python server IP is 101.201.17.155 used at Cityone campus PYThon server IP is 101.201.101.5 used at Citytwo campus My friend email id is peter1@xyz.com use this email for official purpose. 我的经理 email id 是 cooldude@xyz.com 将此 email 用于官方目的。 PYTHON 服务器 IP 是 173.101.255.15 在 Citythree 校园使用 测试服务器 IP7 使用在 Citythree 校园 95.101.101。

问题是找到文件中的所有IP。 我的代码如下:

import re
import os
f1=open("reg1.txt","r")
for line in f1:
    rx=re.search("(\d{1,3}.){3}\d{1,3}",line)
    print(rx)
f1.close()

f2=open("reg1.txt","r")
for line in f2:
    rx=re.search("(\d{1,3}.){3}\d{1,3}",line)
    if rx:
        print(rx.groups())
f2.close()

我的控制台显示结果:

<re.Match object; span=(38, 53), match='192.168.101.124'>
None
<re.Match object; span=(34, 48), match='101.201.17.155'>
<re.Match object; span=(20, 33), match='101.201.101.5'>
None
None
<re.Match object; span=(24, 38), match='173.101.255.15'>
<re.Match object; span=(25, 39), match='95.101.175.101'>
('101.',)
('17.',)
('101.',)
('255.',)
('175.',)

为什么当匹配显示 ip 地址的全跨度时,代码仅打印匹配的 object 的第三部分?

如何打印整个 IP 地址?

使用print(rx.group())代替print(rx.groups())

Match.groups(default=None) 返回一个包含匹配的所有子组的元组,从 1 到模式中的组数。

但在您的情况下,您只捕获 1 个组,即(\d{1,3}.)

https://docs.python.org/3/library/re.html#re.Match.groups

您可以将文件读入一个变量并运行一次对re.findall的调用:

import re

rx = r"(?<!\d)(?: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}(?!\d)"
with open("reg1.txt","r") as f1:
    contents = f1.read()            # Read the file into contents variable
    print(re.findall(rx, contents)) # Extract all IPs

您可以传递f1.read()而不是直接将contents分配给re.findall

该模式取自我之前的答案,我只是为其添加了数字边界, (?<!\d) (左边不允许有数字)和(?!\d) (右边不允许有数字)。 您可以考虑改用\b ,即单词边界。

暂无
暂无

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

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