Regex to Match Number of Subdirectories in a URL


  1. Hi, thanks for writing out this article. It’s been super helpful and is almost exactly what I’m looking for.

    However, I’d like to take “Variation 1” one step further.

    With the example, Regex for exactly one sub-directory:

    This will match any top-level directory, for example: /retail/.

    I’d like to do this, plus 2 and 3 directories deeper, but ideally I want to specify exactly what that directory is. In this example, matching only the /retail/ directory, and all subsequent subdirectories.

    Would love if you’d be able to explain that!

    1. That’s great, glad to hear it was useful!

      If you want to specify a specific directory, you should be able to type it in like this:

      ^/(retail)+/[^/]+/$ (2 subdirectories)
      ^/(retail)+/[^/]+/[^/]+/$ (3 subdirectories)

      Please try that and let me know if there’s any issue.

Leave a Reply

Your email address will not be published.