Python正則表示式物件方法使用
首先使用re模組的compile()方法將正則表示式編譯生成正則表示式物件,然後再使用正則表示式物件提供的方法進行字串處理,使用編譯後的正則表示式物件可以快速的完成字串處理。其字串處理主要包括查詢、匹配、替換、搜尋和分割,這些也是比較常用的操作,具體方法為findall、match、sub、search、split,下面通過幾個例子來做簡單說明。
>>> import re
>>> text="Anhui normal university!"
>>> pattern=re.compile(r'\bn\w+\b') #編譯生成正則表示式物件。
>>> pattern.findall
['normal']
>>> import re
>>> text="I run quickly,you run slowly."
>>> pattern=re.compile(r'\w+ly') #編譯生成正則表示式物件。
>>> pattern.findall(text)#查詢以ly結尾的單詞,即字串中所有副詞。
['quickly', 'slowly']
>>> import re
>>> text="I run quickly,you run slowly."
>>> pattern=re.compile(r'\b[a-zA-Z]{3}\b')#查詢長度為3位的單詞。
>>> pattern.match(text)#從字串開頭開始匹配,不成功則無返回值。
>>> pattern.search(text)#在整個字串搜尋,成功則返回結果。
<_sre.SRE_Match object; span=(2, 5), match='run'>
>>> import re
>>> text="I run quickly,you run slowly."
>>> pattern=re.compile(r'\b[a-zA-Z]{3}\b')
>>> pattern.sub('*',text)#將長度3位的單詞替換位’*’
'I * quickly,* * slowly.'
>>> import re
>>> pattern=re.compile(r'[\s,.\d]+')#根據正則化式進行編譯生成正則物件。
>>> text="I am in house, with lots of pepole. yes,no. 1china 2USA"
>>> pattern.split(text)#按照空白、’,’、‘.’、數字進行分割,並返回所有單詞。
['I', 'am', 'in', 'house', 'with', 'lots', 'of', 'pepole', 'yes', 'no','china', 'USA']