开发者

regular expression to match domain name

Need a regular expression (using PHP) to match a domain name. Examples:

http://sub.domain.com/somefolder/index.html -> domain.com
somedomain.info -> somedomain.info
http://anotherdomain.org/home -> anotherdomain.org
www.subdomain.anothersubdomain.maindomai开发者_JAVA百科n.com/something/ -> maindomain.com


This might not be a job for regexes, but for existing tools in your language of choice. Regexes are not a magic wand you wave at every problem that happens to involve strings. You probably want to use existing code that has already been written, tested, and debugged.

In PHP, use the parse_url function.

Perl: URI module.

Ruby: URI module.

.NET: 'Uri' class


You can use this one as well:

((?>[a-z\-0-9]{2,}\.){1,}[a-z]{2,8})(?:\s|/)

It will match all the domain names found in a given text, while returning the domain found in the first group.


This parses Complete Urls you can check, match objects 2nd element for domain name

(http|ftp|https):\/\/([\w\-_]+(?:(?:\.[\w\-_]+)+))([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?

Works for me :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜