Gautham Gautham - 5 months ago 22
Python Question

Timestamp Regex python (2016-06-22 07:55:35,232 )

I am finding difficult to form a regex for the above timestamp pattern in python. I have to search for the timestamp that matches this pattern in a list in python .

Eg,

2016-06-22 07:55:35,232 [12] INFO

In the above line i have to search 2016-06-22 07:55:35,232 .

I have tried with the following regex but it does not seem to work :

"^\\d{4}[-]?\\d{1,2}[-]?\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2}[,]?\\d{1,3}$"


Kindly help

Thanks

Answer

Your problem is the $ sign at the end -- remove it from your regex. You do not get anything back because $ (end of line) does not match [12] INFO

>>> re.findall("^\\d{4}[-]?\\d{1,2}[-]?\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2}[,]?\\d{1,3}$", '2016-06-22 07:55:35,232 [12] INFO')
[]
>>> re.findall("^\\d{4}[-]?\\d{1,2}[-]?\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2}[,]?\\d{1,3}", '2016-06-22 07:55:35,232 [12] INFO')
['2016-06-22 07:55:35,232']
Comments