这个问题已经有了答案:
What is the difference between re.search and re.match?
8个答案
我试图用Python在一行中找到一个时间戳,我有如下代码,我从Python文档中找到,但是它似乎没有找到想要的子串。
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
我的目标是根据所提供的
regex
从行中提取时间戳。谢谢您。
重复:这个问题(这是一个重复)为我的问题提供了答案,但它仍然是一个不同的问题。我认为最好不要考虑这个问题,因为我无法通过python手册和之前的so问题快速找到答案。
最佳答案
您可以使用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]
输出:
'Jan 3 07:57:39'
关于python - 字符串中的python正则表达式搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48158989/