Pier Pier - 5 months ago 16
Javascript Question

Regex: capture between starting delimiter and optional ending delimiter

With the following string:

foo/:something/bar/:somethingelse


How can I capture
something
and
somethingelse
considering the optional
/
ending delimiter on the second case?

Using
(?<=:)(.*?)(?=\/)
only returns
something
, which makes sense.

So I've tried
(?<=:)(.*?)(?=\/|$)
but it doesn't return
somethingelse
either.

According to Regex101 this
(?=\/|$)
means either
/
or end of the string, so in principle
somethingelse
should be captured.

https://regex101.com/r/gU4uR9/2

What am I missing?

Jan Jan
Answer

As already pointed out by others, the JavaScript regex engine is somewhat crippled (and does not support lookbehinds).
The usual work-around is to match the things before (this consumes characters) and capture the desired substring in a group afterwards:

\/:([^/]+)

See a demo on regex101.com.

In JS code, this would be:

var str = "foo/:something/bar/:somethingelse";
var re = /\/:([^/]+)/g;
var matches = str.match(re);

Thanks to @Wiktor for the clarification of nomenclature.

Comments