我想处理日志文件中的每一行,如果行与我的模式匹配,则提取IP
地址。有几种不同类型的消息,在下面的示例中,我正在使用p1 and
p2`。
我可以逐行读取文件,并且每一行都与每种模式匹配。但
由于可以有更多的模式,因此我想尽可能高效地进行操作。我希望将thos模式编译成一个对象,并且只对每一行进行一次匹配:
import re
IP = r'(?P<ip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
p1 = 'Registration from' + IP + '- Wrong password'
p2 = 'Call from' + IP + 'rejected because extension not found'
c = re.compile(r'(?:' + p1 + '|' + p2 + ')')
for line in sys.stdin:
match = re.search(c, line)
if match:
print(match['ip'])
但是上面的代码不起作用,它抱怨ip
被使用了两次。
实现目标的最优雅方式是什么?
编辑:
我已经根据@Dev Khadka的回答修改了我的代码。
但是我仍在努力如何正确处理多个ip
匹配项。下面的代码显示与p1匹配的所有IP:
for line in sys.stdin:
match = c.search(line)
if match:
print(match['ip1'])
但是有些行与p1
不匹配。它们匹配p2
。即,我得到:
1.2.3.4
None
2.3.4.5
...
当我不知道它是p1
,p2
,...时,如何打印匹配的ip?我只需要IP。我不在乎它匹配哪种模式。
参考方案
您可以考虑安装出色的regex
模块,该模块支持许多先进的正则表达式功能,包括branch reset groups,旨在完全解决您在本问题中概述的问题。分支重置组用(?|...)
表示。分支复位组中具有不同位置的相同位置或名称的所有捕获组共享相同的捕获组以进行输出。
请注意,在下面的示例中,匹配的捕获组成为命名的捕获组,因此您不需要遍历多个组来搜索非空组:
import regex
ip_pattern = r'(?P<ip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
patterns = [
'Registration from {ip} - Wrong password',
'Call from {ip} rejected because extension not found'
]
pattern = regex.compile('(?|%s)' % '|'.join(patterns).format(ip=ip_pattern))
for line in sys.stdin:
match = regex.search(pattern, line)
if match:
print(match['ip'])
演示:https://repl.it/@blhsing/RegularEmbellishedBugs
用大写字母拆分字符串,但忽略AAA Python Regex - python我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…
在返回'Response'(Python)中传递多个参数 - python我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…
Python exchangelib在子文件夹中读取邮件 - python我想从Outlook邮箱的子文件夹中读取邮件。Inbox ├──myfolder 我可以使用account.inbox.all()阅读收件箱,但我想阅读myfolder中的邮件我尝试了此页面folder部分中的内容,但无法正确完成https://pypi.python.org/pypi/exchangelib/ 参考方案 您需要首先掌握Folder的myfo…
R'relaimpo'软件包的Python端口 - python我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。
Python ThreadPoolExecutor抑制异常 - pythonfrom concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED def div_zero(x): print('In div_zero') return x / 0 with ThreadPoolExecutor(max_workers=4) as execut…