Python - 受約束搜尋



搜尋結果出來後,我們經常需要對現有搜尋結果的某一部分進行更深層次的搜尋。例如,在給定的文字主體中,我們的目標是獲取網址,並提取網址的不同部分(如協議、域名等)。在這種情況下,我們需要藉助分組函式,該函式可根據分配的正則表示式將搜尋結果劃分為不同的組。我們透過使用圓括號將可搜尋部分與需要匹配的固定單詞分離開來,建立此類組表示式。

import re
text = "The web address is https://tutorialspoint.tw"

# 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://tutorialspoint.tw
The protocol:  https
The doman name:  www.tutorialspoint
The TLD:  com
廣告
© . All rights reserved.