【问题标题】:regular expression to match domain name匹配域名的正则表达式
【发布时间】:2011-05-20 12:24:50
【问题描述】:

需要一个正则表达式(使用 PHP)来匹配一个域名。例子:

http://sub.domain.com/somefolder/index.html -> domain.com
somedomain.info -> somedomain.info
http://anotherdomain.org/home -> anotherdomain.org
www.subdomain.anothersubdomain.maindomain.com/something/ -> maindomain.com

【问题讨论】:

标签: php regex


【解决方案1】:

这可能不是正则表达式的工作,而是你选择的语言中的现有工具。正则表达式不是你对碰巧涉及字符串的每个问题挥舞的魔杖。您可能希望使用已经编写、测试和调试过的现有代码。

在 PHP 中,使用 parse_url 函数。

Perl:URI module.

鲁比:URI module.

.NET:'Uri' class

【讨论】:

    【解决方案2】:

    你也可以用这个:

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

    它将匹配在给定文本中找到的所有域名,同时返回在第一组中找到的域。

    【讨论】:

      【解决方案3】:

      这会解析您可以检查的完整网址,匹配对象的第二个域名元素

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

      为我工作:)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-20
        • 1970-01-01
        • 1970-01-01
        • 2020-03-28
        • 1970-01-01
        相关资源
        最近更新 更多