user2829222
user2829222

Reputation: 65

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

Upvotes: 0

Views: 3825

Answers (3)

Percy Contreras
Percy Contreras

Reputation: 1

Your pattern works fine, but you are only matching at the end of string because of $.

If you want to match just this:

2016-06-22 07:55:35,232

You can use this regular expression.

(?P<date>\d{4}[-]?\d{1,2}[-]?\d{1,2} \d{1,2}:\d{1,2}:\d{1,2}[,]?\d{1,3})

You can try it online at Regex101

Upvotes: 0

Andrew
Andrew

Reputation: 388

Encapsulating your regex with ^ and $ ensures that the string will only ever be matched by your regex if the regex matches the entire string, since ^ signifies beginning of the string and $ signifies the end. If you want it to be able to match anywhere, you should remove both the ^ and the $. If you only want the timestamp to match when it is the start of the string, keep the ^ and just remove the $, which is what is currently blocking you from getting a match since you have [12] INFO at the end of your string.

Upvotes: 0

UltraInstinct
UltraInstinct

Reputation: 44464

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']

Upvotes: 2

Related Questions