re模組中match物件中的方法和屬性
match物件的方法和屬性
屬性和方法 |
描述 |
pos |
搜尋的開始位置 |
endpos |
搜尋的結束位置 |
string |
搜尋的字串 |
re |
當前使用的正則表示式物件 |
lastindex |
最後匹配的組索引 |
lastgroup |
最後匹配的組名 |
group(index) |
某個組匹配的結果 |
groups() |
所有分組的匹配結果,每個分組組成的結果以列表返回 |
groupdict() |
返回組名作為key,每個分組的匹配結果作為value的字典 |
start([group]) |
獲取組的開始位置 |
end([group]) |
獲取組的結束位置 |
span([group]) |
獲取組的開始和結束位置 |
expand(template) |
使用組的匹配結果來替換template中的內容,並把替換後的字串返回 |
>>> import re
>>> m = re.match(r"(\w{5}) \s(\w+) \s(\b\w{2}\b)", "china is ok")#分成3組,一個括
#號表示一組
>>> m.group(0)
'china is ok'
>>> m.group(1)#根據組號進行輸出,預設為1,2……n
'china'
>>> m.group(2)
'is'
>>> m.group(3)
'ok'
>>>import re
>>> m = re.match(r"(?P<province>\w+) \s(?P<city>\w+)", "Anhui Anqing")#對每組進#行重新命名
>>> m.group("province")#第一組名為province
'Anhui'
>>> m.group("city")#第二組名為city
'Anqing'
>>>import re
>>> m = re.match(r"(?P<province>\w+) \s(?P<city>\w+)", "Anhui Anqing")
>>> m.groupdict().keys()#獲取返回的列表中的key
dict_keys(['province', 'city'])
>>> m.groupdict().values()#獲取返回的列表中的value
dict_values(['Anhui', 'Anqing'])
>>> m.re.pattern #獲取當前使用的正則表示式
'(?P<province>\\w+) \s(?P<city>\\w+)'