如何提取行尾(如果是数字)

cda*_*dac 2 python regex list

我下面有一个文本文件,如果行的最后一部分是数字,则尝试提取字符串

4:16:09PM - xx yy DOS activity from 10.0.0.45
9:43:44PM - xx yy 1A disconnected from server
2:40:28AM - xx yy 1A connected
1:21:52AM - xx yy DOS activity from 192.168.123.4
Run Code Online (Sandbox Code Playgroud)

我的密码

with open(r'C:\Users\Desktop\test.log') as f:
    for line in f:
        dos= re.findall(r'\d',line.split()[-1])
        print (list(dos))
Run Code Online (Sandbox Code Playgroud)

我的出

['1', '0', '0', '0', '4', '5']
[]
[]
['1', '9', '2', '1', '6', '8', '1', '2', '3', '4']
Run Code Online (Sandbox Code Playgroud)

预期

['10.0.0.45','192.168.123.4']

Emm*_*mma 6

我猜,

(?m)(?:\d+\.){3}\d+$
Run Code Online (Sandbox Code Playgroud)

可能只是提取那些所需的IP。

正则演示

测试

import re

string = '''
4:16:09PM - xx yy DOS activity from 10.0.0.45
9:43:44PM - xx yy 1A disconnected from server
2:40:28AM - xx yy 1A connected
1:21:52AM - xx yy DOS activity from 192.168.123.4
'''

expression = r'(?m)(?:\d+\.){3}\d+$'


print(re.findall(expression, string))

Run Code Online (Sandbox Code Playgroud)

输出量

['10.0.0.45', '192.168.123.4']
Run Code Online (Sandbox Code Playgroud)

如果您希望简化/更新/探索该表达式,请在regex101.com的右上方面板中进行说明。如果您有兴趣,可以观看匹配的步骤或在此调试器链接中对其进行修改。调试器演示了RegEx引擎如何逐步使用一些示例输入字符串并执行匹配过程。


RegEx电路

jex.im可视化正则表达式:

在此处输入图片说明