Regex to match specific domain and it's subfolder

Viewed 385

I want to match a particular domain and its subdomain, no matter how it's entered. In the following example, I want to match all ´test.comif nothing comes after it (only a slash or query strings) OR if a specific folder follows it in this case it's named as:subfolder`. Again the subfolder could have / or query strings after.

Right now I have the following regex:

^(?:\S+://)?[^/]+/?$

The problem though is that it matches ANY domains, which is not what I need. I want to match a specific domain and a specific subfolder.

How is this possible?

2 Answers

You may use this regex:

^(?:https?://)?(?:www\.)?test\.com(?:/subfolder)?/?(?:\?\S*)?$

RegEx Demo

RegEx Demo:

  • ^: Start
  • (?:https?://)?: *optionally* match http://orhttps://`
  • (?:www\.)?: optionally match www.
  • test\.com: match test.com
  • (?:/subfolder)?: optionally match /subfolder
  • /?: optionally match a trailing /
  • (?:\?\S*)?: optionally match query string starting with ?
  • $: End

With your shown samples, could you please try following.

^(?:(?:https?:\/\/)(?:www\.)?)?test\.com(?:(?:(?:\/)?(?:\/subfolder\/?)?(?:\/\?\S+\/?)?)?(?:\?\S+)?)?(?:\/)?$

Online demo for above regex

Explanation: Adding detailed explanation for above.

^                            ##Starting of match here by caret sign.
(?:                          ##Starting non-capturing group here.
   (?:https?:\/\/)           ##In this non-capturing group which has http/https// in it to match.
   (?:www\.)?                ##In this non-capturing group keeping www. as an optional here.
)?                           ##Closing very first non-capturing group here.
test\.com                    ##Matching string test.com here. (1, calling it 1 for explanation purposes)
(?:                          ##Starting a non-capturing group here.
   (?:                       ##Starting one more non-capturing group here.(2, calling it for explanation purposes only)
      (?:\/)?                ##Matching / optional in a non-capturing group here.
      (?:\/subfolder\/?)?    ##Matching /subfolder /(as optional) and whole non-capturing group as optional.
      (?:\/\?\S+\/?)?        ##Matching /? and all non-space characters followed by /(optional) in non-capturing group, keep this optional.
   )?                        ##Closing (2) non-capturing group here.
   (?:                       ##Starting non-capturing group here.
      \?\S+                  ##Matching ? non-spaces values here.
   )?                        ##Closing non-capturing group here.
)?                           ##Closing (1) non-capturing group here.
(?:                          ##Starting non-capturing group here.
   \/                        ##Matching single / here.
)?                           ##Closing non-capturing group here, keeping it optional.
$                            ##Mentioning $ to tell the end of value(match).
Related