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?
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.
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.
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.
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.
Try this:
/objects/(.*?)(/|$)
It simply does a non-greedy match between /objects/
and either a slash or eof
This regex matches either EOF or a certain character (i.e. /).
(?<=\/objects\/obj_)(.+?)(?=\/|$)
Here is a demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With