Positive lookahead to match '/' or end of string

devights picture devights · Aug 29, 2012 · Viewed 7k times · Source

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):

  • /objects/obj_asd-1234-special
  • /objects/obj_xyz-15434/members
  • /objects/obj_aasdfaeastd-15d44/other/asdf

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?

Answer

Bohemian picture Bohemian · Aug 29, 2012

Try this:

/objects/(.*?)(/|$)

It simply does a non-greedy match between /objects/ and either a slash or eof