Reputation: 283
I'm trying to do a positive lookahead to match an object ID in a given URL, regardless of where that object ID is in the URL. The idea being to match until either a '/' or the end of the string. Here are some sample strings (bold being the ID I want to match):
Using this: objects/obj_(.+?)(?=/) matches the latter two as they both have a trailing slash. I read that the lookahead supports regex as the matching character, so I tried this objects/obj_(.+?)(?=(/|$)) to no avail. Any thoughts?
Upvotes: 13
Views: 14927
Reputation: 4217
This regex matches either EOF or a certain character (i.e. /).
(?<=\/objects\/obj_)(.+?)(?=\/|$)
Here is a demo.
Upvotes: 10
Reputation: 424983
Try this:
/objects/(.*?)(/|$)
It simply does a non-greedy match between /objects/
and either a slash or eof
Upvotes: 9
Reputation: 91299
You don't need to use a positive lookahead:
/objects/([^/]+).*
And then, the first group will hold your id value.
Here's an example in Python:
>>> import re
>>> p = re.compile('/objects/([^/]+).*')
>>> p.match("/objects/obj_asd-1234-special").group(1)
'obj_asd-1234-special'
>>> p.match("/objects/obj_xyz-15434/members").group(1)
'obj_xyz-15434'
>>> p.match("/objects/obj_aasdfaeastd-15d44/other/asdf").group(1)
'obj_aasdfaeastd-15d44'
Upvotes: 3