1

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

4
  • so you want to match everything after tom? Commented Aug 6, 2016 at 2:41
  • Good morning @rock321987, yes that is correct. I want to match everything after tom (except spaces at the beginning/end) and only if a delmiter was found. Commented Aug 6, 2016 at 2:45
  • see if this works..I have replace \s with space as \s matches new line Commented Aug 6, 2016 at 2:53
  • Solid work @rock321987! Thank you very much for your help. Please post this as an official answer if you want, so I can give you kudos. Commented Aug 6, 2016 at 2:56

1 Answer 1

1

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.