1

I am trying to write a regex that matches a url of the following format:

/api/v1/users/<mongo_object_id>/submissions

Where an example of a mongo_object_id is 556b352f87d4693546d31185. I have cooked up the following pattern, but it does not seems to work.

/api/v1/users\\/(?=[a-f\\d]{24}$)(\\d+[a-f]|[a-f]+\\d)\\/submissions

Any help is appreciated.

3
  • 3
    can you give example of mongo_object_id ? Commented May 31, 2015 at 16:37
  • 556b352f87d4693546d31185 (also added it in post) Commented May 31, 2015 at 16:42
  • Please remove the tag from your title. See this question for more information. Commented Jun 1, 2015 at 14:58

2 Answers 2

6

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']
Sign up to request clarification or add additional context in comments.

2 Comments

Out of curiosity, why do you do a lookahead then a match?
I was just fixing original regex, it wasn't clear on this point, but it doesn't really makes sense, thanks for feedback.Actually with more then 24 chars lookahead solution would fail
5

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.