Regex to match simple domain

感情迁移 提交于 2019-12-18 03:58:09

问题


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.

回答1:


^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"




回答2:


You can probably use to just match the domain name part of a URL:

/^(?:http(?:s)?:\/\/)?(?:[^\.]+\.)?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

UPDATE: To match full URL, not just domain name part, use:

/^(?:http(?:s)?:\/\/)?(?:[^\.]+\.)?example\.com(\/.*)?$     



回答3:


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.




回答4:


The following works in Java,

^(http:|https:|)[/][/]([^/]+[.])*example.com$

and matches your test cases, and doesn't match cases like

http://www.google.com/http://example.com




回答5:


This will correctly match the URL for any variation of the below, plus anything after .com

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

Result will be either true or false

const result = /^(http(s)?(:\/\/))?(www\.)?example\.com(\/.*)?$/.test(value); 


来源:https://stackoverflow.com/questions/8830411/regex-to-match-simple-domain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!