Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Positive lookahead to match '/' or end of string

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?

like image 244
devights Avatar asked Aug 29 '12 00:08

devights


People also ask

How do you use positive lookahead?

The positive lookahead construct is a pair of parentheses, with the opening parenthesis followed by a question mark and an equals sign. You can use any regular expression inside the lookahead (but not lookbehind, as explained below). Any valid regular expression can be used inside the lookahead.

What does positive lookahead mean?

Positive lookahead: (?= «pattern») matches if pattern matches what comes after the current location in the input string. Negative lookahead: (?! «pattern») matches if pattern does not match what comes after the current location in the input string.

What is lookahead assertion in regex?

A lookahead assertion has the form (?= test) and can appear anywhere in a regular expression. MATLAB® looks ahead of the current location in the text for the test condition. If MATLAB matches the test condition, it continues processing the rest of the expression to find a match.

What is lookahead and Lookbehind?

The lookbehind asserts that what immediately precedes the current position is a lowercase letter. And the lookahead asserts that what immediately follows the current position is an uppercase letter.


2 Answers

Try this:

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

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

like image 150
Bohemian Avatar answered Sep 22 '22 06:09

Bohemian


This regex matches either EOF or a certain character (i.e. /).

(?<=\/objects\/obj_)(.+?)(?=\/|$)

Here is a demo.

like image 22
sluijs Avatar answered Sep 22 '22 06:09

sluijs