約束搜尋


很多時候,在得到搜尋結果之後,我們需要更深入地搜尋現有搜尋結果的一部分。 例如,在給定的文字主體中,我們的目標是獲取Web地址,並提取Web地址的不同部分,如協定,域名等。在這種情況下,需要借助用於劃分的組功能 搜尋結果以各個組為基礎,分配正規表示式。 我們通過使用可搜尋部分周圍的括號分隔主搜尋結果來建立這樣的組表示式,不包括想要匹配的固定單詞。

import re
text = "The web address is https://www.tw511.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.tw511.com
The protocol:  https
The doman name:  www.yiibai
The TLD:  com