I got log file:
[2022-02-21 11:23:56.919] text text text text text text text text
[2022-02-21 11:23:58.868] text text text text text text text text
[2022-02-21 11:23:58.923] text text text text text text text text
Does anybody know how to get a regular expression for timestamps only?
CodePudding user response:
You can use Regex101 to test your patterns.
Try this one: \[(. )\]
CodePudding user response:
You don't really need re for this because the timestamp is fixed width. If you insist on using a regular expression then:
import re
t = '[2022-02-21 11:23:56.919] text text text text text text text text'
if (m := re.search(r'\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}\.\d{3}', t)):
print(m[0])
...or...
if (m := re.search(r'\[(. )\]', t)):
print(m[0][1:-1])
Output:
2022-02-21 11:23:56.919
However:
print(t[1:24])
...would give the same result