字符串中的python正则表达式搜索

Air*_*ezx 4 python regex

我试图使用Python在一行中找到一个时间戳,我有以下代码是从SO和Python Docs获得的,但似乎找不到所需的子字符串。

import re

line = "Jan  3 07:57:39 Kali sshd[1397]: Failed password for root from 172.16.12.55 port 34380 ssh2"
regex = "[0-9]{2}:[0-9]{2}:[0-9]{2}"
p = re.compile(regex)
m = p.match(line)
print m

# Output: None
Run Code Online (Sandbox Code Playgroud)

我的目标是根据regex提供的内容从行中提取时间戳。

谢谢。

重复:问题(这是重复的问题)为我的问题提供了答案,但这仍然是另一个问题。我认为最好不要再考虑像我这样的人了,因为我无法通过Python手册和先前的SO问题*迅速*找到答案。

Aja*_*234 6

您可以使用re.findall

import re
line = "Jan  3 07:57:39 Kali sshd[1397]: Failed password for root from 172.16.12.55 port 34380 ssh2"
new_line = re.findall('^[a-zA-Z]+\s+\d+\s+[\d\:]+', line)[0]
Run Code Online (Sandbox Code Playgroud)

输出:

'Jan  3 07:57:39'
Run Code Online (Sandbox Code Playgroud)