Leigh
Leigh

Reputation: 3

Regex to Match Number of Subdirectories in a URL

I found an article that almost covered my exact need. However, it needs to be adjusted a bit and I can't quite figure it out.

VARIATION 1: EXACTLY X NUMBERS OF SUB-DIRECTORIES, WITH TRAILING SLASH This variation assumes each subdirectory ends in a trailing slash.

Regex for exactly one sub-directory ^/[^/]+/$

example matching URL path: /retail/

Regex for exactly two sub-directories ^/[^/]+/[^/]+/$

example matching URL path: /retail/clothing/

I would like to adjust these two rules to match a specific directory.

In my case, I have a site that has multiple top-level directories (products and stores, each with 2 additionally subdirectories).

I would like to create a regex rule to only target /products/ plus the following 3 subdirectories.

Upvotes: 0

Views: 3684

Answers (1)

Bill Stafford
Bill Stafford

Reputation: 26

I don’t have a system to test this, but I think you can use the ‘?’ and parens to add the variable sub-dirs on your base match for “/products/“.

The base regex would be “^/products/$”. Then to match 0 or 1 subdirectories, you could add “([^/]+/)?” Add three of these and I think you have the regex to match your base plus 0 to 3 subdirectories. I think that is what you were asking for.

^/products/([^/]+/)?([^/]+/)?([^/]+/)?$

The equivalent RE worked in Emacs for these test lines:

/products/
/products/a/
/products/a/b/
/products/a/b/c/

And did not match this:

/products/a/b/c/d/

If you always wanted the 3 subdirectories, drop the ‘?’s to make the extras required.

^/products/[^/]+/[^/]+/[^/]+/$

Hope this helps!

Upvotes: 1

Related Questions