Python 约束搜索
很多时候,在我们获得搜索结果后,我们需要在现有搜索结果的一部分中进行更深层次的搜索。例如,在给定的文本正文中,我们的目标是获取网址,并提取网址的不同部分,如协议、域名等。在这种情况下,我们需要借助用于划分的 group 功能根据分配的正则表达式将搜索结果分成不同的组。我们通过在可搜索部分周围使用括号分隔主搜索结果来创建这样的组表达式,不包括我们想要匹配的固定单词。
import re text = "The web address is https:// www.newbiego.com" # Taking ":// "和"." 分隔组 result = re.search('([\w.-]+):// ([\w.-]+)\.([\w.-]+)', 文本) 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.newbiego.com The protocol: https The doman name: www.newbiego The TLD: com