字符串中的Python正则表达式搜索
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48158989/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python regex search in string
提问by Airwavezx
I'm trying to locate a timestamp in a line using Python, I have the following code which I got from SO and Python Docs, but it doesn't seem to spot the desired substring.
我正在尝试使用 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
My goal is to extract the timestamp from the line according to the regex
provided.
我的目标是根据regex
提供的行从行中提取时间戳。
Thank you.
谢谢你。
Duplicate: The question (which this is a duplicate of) offers the answer to my question, but it's still a different question. I think it's best to keep this one as well out of consideration for people like me in the future, as I wasn't able to find the answer *QUICKLY*through Python Manual & previous SO questions.
重复:这个问题(这是重复的)为我的问题提供了答案,但它仍然是一个不同的问题。我认为最好不要让像我这样的人将来考虑这个问题,因为我无法通过 Python 手册和以前的 SO 问题*快速*地找到答案。
回答by Ajax1234
You can use re.findall
:
您可以使用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]
Output:
输出:
'Jan 3 07:57:39'
回答by Luca
You should try re.findall
你应该试试 re.findall
import re
line = "Jan 3 07:57:39 Kali sshd[1397]: Failed password for root from172.16.12.55 port 34380 ssh2"
pattern = "[0-9]{2}:[0-9]{2}:[0-9]{2}"
matches = re.findall(pattern, line)
for match in matches:
print(match)