Python - 约束搜索

  • 简述

    很多时候,在我们获得搜索结果后,我们需要在现有搜索结果的一部分中进行更深层次的搜索。例如,在给定的文本正文中,我们的目标是获取网址,并提取网址的不同部分,如协议、域名等。在这种情况下,我们需要借助用于划分的 group 函数根据分配的正则表达式将搜索结果分成不同的组。我们通过在可搜索部分周围使用括号分隔主搜索结果来创建这样的组表达式,不包括我们想要匹配的固定单词。
    
    import re
    text = "The web address is https://www.jc2182.com"
    # Taking "://" and "." to separate the groups 
    result = re.search('([\w.-]+)://([\w.-]+)\.([\w.-]+)', text)
    if result :
        print "The main web Address: ",result.group()
        print "The protocol: ",result.group(1)
        print "The doman name: ",result.group(2) 
        print "The TLD: ",result.group(3) 
    
    当我们运行上述程序时,我们得到以下输出 -
    
    The main web Address:  https://www.jc2182.com
    The protocol:  https
    The doman name:  www.jc2182
    The TLD:  com