Python - Regex To Match Url With Mongo Object Id
I am trying to write a regex that matches a url of the following format: /api/v1/users//submissions Where an example of a mongo_object_id is 556b352f87d4693
Solution 1:
This will do (considering 24 hex chars), using raw keyword before string so no need to escape with double slashes:
r'\/api\/v1\/users\/([a-f\d]{24})\/submissions'
Python console:
>>> re.findall(r'\/api\/v1\/users\/([a-f\d]{24})\/submissions','/api/v1/users/556b352f87d4693546d31185/submissions')
['556b352f87d4693546d31185']
Solution 2:
It looks like an object's ID is a hexadecimal number, which means that it's matched by something as simple as this:
[0-9a-f]+
If you want to make sure it's always 24 characters:
[0-9a-f]{24}
Toss that between the slashes:
/api/v1/users/([0-9a-f]{24})/submissions
And it should work.
Note: You will probably have to escape the slashes, depending on how Python's regex syntax works. If I remember right, you can do this:
import re
re.findall(r'/api/v1/users/([0-9a-f]{24})/submissions', url)
or
re.findall(r'/api/v1/users/([0-9a-f]{24})/submissions', url, re.I)
if you wanna make the whole thing case-insensitive.
Post a Comment for "Python - Regex To Match Url With Mongo Object Id"