Steve Muster Steve Muster - 4 months ago 13
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)

Regex:

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





Match against:

music/tom/foldername
music/tom/folder name
music/tom/foldername/folder2





Expected results:

enter image description here


[MATCH 1]
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
parents





Regex Demo: https://regex101.com/r/yN2kK2/1




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

str.substr(str.lastIndexOf('/'))


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

Answer

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