【问题标题】:print a list of valid log file entries in python 3 regex在 python 3 regex 中打印有效日志文件条目的列表
【发布时间】:2019-03-21 05:14:59
【问题描述】:

我是 python 新手。我想打开一个文件 logs.txt 并匹配每一行(日志条目)中的所有 IP 地址。

然后我会打印带有 IP 地址的日志条目的数量/计数。 到目前为止我所拥有的:

import re
#read the file
file = open("logile.txt")
lineList = []
for line in file:
    match = re.search( r'^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}', line )
    if match:
        print("IP found in this line is:  ", match.group())

现在我想打印具有此 IP 地址的日志条目数。如何将带有 IP 的每一行附加到我的 lineList 并打印计数?

【问题讨论】:

  • 你的问题是什么?
  • 我的帖子最后一行@DYZ
  • 我已经编辑了????

标签: regex python-3.x list iteration match


【解决方案1】:
import re
file = open("logfile.txt")
lineList = []
count = 0
for ln, line in enumerate(file):
    match = re.search( r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b', line )
    if match:
        count += 1
        print("Match #{}: IP found in line {} is: {}".format(count, ln+1, match.group()))
        lineList.append(match.group())

注意正则表达式中的额外反斜杠和word boundary anchor 以防止错误匹配。此外,由于 ^ 锚点,正则表达式将仅匹配行首的 IP 地址。

【讨论】:

  • 嘿@Tim 有一个错误:SyntaxError: invalid syntax - lineList.append(match.group())
  • 啊,是的,上一行缺少)
【解决方案2】:

如果 IP 存在于一行中,您可以使用肯定的前瞻来断言:

(?=.*\d{1,3}(?:\.\d{1,3}){3}.*).+

解释:

(?=...) - 正向预测

.* - 匹配零个或多个任意字符

\d{1,3} - 匹配 1 到三个数字

(?:...) - 非捕获组

\.\d{1,3} - 从字面上匹配点和一个最多三个数字

(?:\.\d{1,3}){3} - 匹配\.\d{1,3} 3 次

如果断言为真,则用.+匹配整行

Demo

【讨论】:

    猜你喜欢
    • 2021-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-21
    相关资源
    最近更新 更多