Steve Muster Steve Muster - 1 year ago 66
Javascript Question

Javascript Regex: Strip path until last occurence in a capturing group

I'm trying to filter a path in the first capturing group.

Currently the first capturing group extracts the path including its parent paths.

While this behavior is completely fine, I don't want the path itself to be included. Capture group one should only extract the parent paths if any.

Capture group 2 must stay as is. (See the red numbers in picture below)


/^(?:music|pictures)\/tom((?:\/((?:[\w-]+(?:[ ]+[\w-]+)*)))*)$/gm

Match against:

music/tom/folder name

Expected results:

enter image description here

I expect the first match (green) to be empty, since it
does not have any parents nor childs

[MATCH 2] the same as [MATCH 1]

[MATCH 3] I expect the first match (green) to only contain the

Regex Demo:

Technically I could just keep my regex and use Javascript for the expected behavior:


However, I appreciate if this could be archived with the regex as well.

Answer Source

You can modify your regex to achieve desired behavior like

^(?:music|pictures)\/tom(\/(?:[\w-]+(?:[ ]+[\w-]+)*))*(\/(?:[\w-]+(?:[ ]+[\w-]+)*))$
                        Captures the parent directory

Regex Demo

If you consider everything after /tom (and just before last) as parent directory, you can modify the regex as

^(?:music|pictures)\/tom((?:\/(?:[\w-]+(?:[ ]+[\w-]+)*))*)(\/(?:[\w-]+(?:[ ]+[\w-]+)*))$

Regex Demo