Q:

Regex to match simple domain

I am trying to match a simple domain: example.com
But all combinations of it.
How would I do this to cover:

https://example.com
http://www.example.com
etc.

A:

^https?://([\w\d]+\.)?example\.com$

using code:
var result = /^https?:\/\/([a-zA-Z\d-]+\.){0,}example\.com$/.test('https://example.com');
// result is either true of false

I improved it to match like "http://a.b.example.com"

A:

You can probably use to just match the domain name part of a URL:
/^(?:https?:\/\/)?(?:[^.]+\.)?example\.com(\/.*)?$

It will match any of following strings:
https://example.com
http://www.example.com
http://example.com
https://example.com
www.example.com
example.com

 

RegEx Demo
RegEx Details:

^: Start
(?:https?:\/\/)?: Match http:// or https://
(?:[^.]+\.)?: Optionally Match text till immediately next dot and dot
example\.com: Match example.com
(\/.*)?: Optionally Match / followed by 0 or more of any characters
$: End

A:

A more generic example I used:
/http(?:s)?:\/\/(?:[\w-]+\.)*([\w-]{1,63})(?:\.(?:\w{3}|\w{2}))(?:$|\/)/i

Note that this solution doesn't pick up the correct label for 5 character TLDs. Example:
http://mylabel.co.uk

Would be picked up as 'co' instead of 'mylabel', but
http://mylabel.co

would be matched correctly as 'mylabel'. The regex was good enough for me even with this limitation.
Note that the 63 character limit for the label is an RFC specification. Hope this helps anyone looking for the same answer in the future.

