Regex To Extract Domain Name From URL

A regular expression to extract a domain name or subdomain (with a protocol like HTTPS, HTTP) from a given URL.

/^(?:https?:\/\/)?(?:[^@\/\n]+@)?(?:www\.)?([^:\/?\n]+)/

Matches:

  • https://regexpattern.com/post.php?post=145&action=edit
  • http://regexpattern.com/post.php?post=145&action=edit
  • https://sub.regexpattern.com/post.php?post=145&action=edit
  • regexpattern.com/post.php?post=145&action=edit

Non-matches:

  • ftp://regexpattern.com/post.php?post=145&action=edit
  • //regexpattern.com/post.php?post=145&action=edit

See Also:

Regex Is Copied!