close

 如何運用Python re 模組

Python 中,只要引入「re」模組即可。模組中最常用的函式,就是 search 函式了。 

import re

text = "abcd1234efghijkl1234mnopqrs1234tuvwxyz1234"

match = re.search(r".. (\d+) ", text)

if match:

    # group 函式會回傳截取的內容,0 代表自己,

            1 代表第一個截取的內容

    print(match.group(0)) 

    print(match.group(1)) 

要同時找多個符合的結果,則可以使用 re.findall 函式:

import re

text = "abcd1234efghijkl1234mnopqrs1234tuvwxyz1234"

print(re.findall(r"..(\d+)", text)) 

若需要多次同一 regex 搜尋,可以使用 re.compile 函式預先處理 regex 以增加效能。

import re

 

text = "abcd1234efghijkl1234mnopqrs1234tuvwxyz1234"

regex = re.compile(r"..(\d+)")

regex.findall(text) 

text = "gogog33991llmkiop88991zzhhhghj443321"

regex.findall(text) 

 

arrow
arrow

    阿丹 發表在 痞客邦 留言(0) 人氣()