Steve Muster Steve Muster - 1 year ago 43
Javascript Question

Javascript Regex: Match additionals based on path delimiter

I'm trying to match folders/files in a repeated manner - based on the path delimiter




Explanation of the regex above:

// Match a base-directory called music/pictures
// Match if directory tom exist
// If delimiter was found, match delimiter and word-character and hypen (no spaces etc at the beginning)
// Match spaces, word-characters and hypen (no spaces etc at the end)
//If delimiter was not found, end string
//End string

Everytime the delimiter
is found (positive lookahead), it should also match the remaining conditions. It works very well except for when a subfolder hits the regex.


music/tom/folder name

music/tom/foldername/folder2 <--- Does not match

As you can see the last path cannot be matched. How can I extend/improve the regex in order to match subfolders as well?

Regex Demo:

Answer Source

You can use this regex to get what you want

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

Regex Demo


  • You don't need lookahead when you already know what you require as next character.
  • - is not required to be escaped when it is used in first/last of character class.