使用正则表达式提取域

2024-09-27 04:23:31 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有这些网址。

http://abdd.eesfea.domainname.com/b/33tA$/0021/file
http://mail.domainname.org/abc/abc/aaa
http://domainname.edu 

我只想把“domainame.com”或“domainname.org”或“domainname.edu”提取出来。 我该怎么做?

我想,我需要在“com | org | edu…”之前找到最后一个“点”,并打印出从这个“点”的上一个点到下一个点(如果有的话)的内容。

需要关于常规表达式的帮助。 谢谢!!! 我正在使用Python。


Tags: orgcomhttp内容mail常规file网址
3条回答

如果你想走regex路线。。。

RFC-3986是有关uri的权威。Appendix B提供了此regex以将一个regex分解为其组件:

re_3986 = r"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?"
# Where:
# scheme    = $2
# authority = $4
# path      = $5
# query     = $7
# fragment  = $9

这是一个增强的、Python友好的版本,它利用了命名的捕获组。它以工作脚本中的函数表示:

import re

def get_domain(url):
    """Return top two domain levels from URI"""
    re_3986_enhanced = re.compile(r"""
        # Parse and capture RFC-3986 Generic URI components.
        ^                                    # anchor to beginning of string
        (?:  (?P<scheme>    [^:/?#\s]+):// )?  # capture optional scheme
        (?:(?P<authority>  [^/?#\s]*)  )?  # capture optional authority
             (?P<path>        [^?#\s]*)      # capture required path
        (?:\?(?P<query>        [^#\s]*)  )?  # capture optional query
        (?:\#(?P<fragment>      [^\s]*)  )?  # capture optional fragment
        $                                    # anchor to end of string
        """, re.MULTILINE | re.VERBOSE)
    re_domain =  re.compile(r"""
        # Pick out top two levels of DNS domain from authority.
        (?P<domain>[^.]+\.[A-Za-z]{2,6})  # $domain: top two domain levels.
        (?::[0-9]*)?                      # Optional port number.
        $                                 # Anchor to end of string.
        """, 
        re.MULTILINE | re.VERBOSE)
    result = ""
    m_uri = re_3986_enhanced.match(url)
    if m_uri and m_uri.group("authority"):
        auth = m_uri.group("authority")
        m_domain = re_domain.search(auth)
        if m_domain and m_domain.group("domain"):
            result = m_domain.group("domain");
    return result

data_list = [
    r"http://abdd.eesfea.domainname.com/b/33tA$/0021/file",
    r"http://mail.domainname.org/abc/abc/aaa",
    r"http://domainname.edu",
    r"http://domainname.com:80",
    r"http://domainname.com?query=one",
    r"http://domainname.com#fragment",
    r"www.domainname.com#fragment",
    r"https://domainname.com#fragment",
    ]
cnt = 0
for data in data_list:
    cnt += 1
    print("Data[%d] domain = \"%s\"" %
        (cnt, get_domain(data)))

有关根据RFC-3986分离和验证URI的更多信息,您可能想看一看我一直在写的一篇文章:Regular Expression URI Validation

除了贾斯的回答。 如果您不想使用urlparse,只需拆分URL

协议条(http://or https://) 您刚刚按第一个出现的“/”拆分了字符串。这会给你留下这样的东西: 第二个URL上的“mail.domainname.org”。然后可以按“.”拆分,只需按[-2]从列表中选择最后两个

这将始终产生domainname.org或其他内容。如果你把协议去掉了,并且URL是有效的。

我只想使用urlparse,但这是可以做到的。 不知道雷鬼的事,但我会这么做的。

相关问题 更多 >

    热门问题