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

/
.

Regex:

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


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/foldername

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: https://regex101.com/r/oG9bC3/1

Answer

You can use this regex to get what you want

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

Regex Demo

NOTE

  • 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.