這一節主要學習一下compile()函數和group()方法
1. re.compile()
compile 函數用於編譯正則表達式,生成一個正則表達式( Pattern )對象,然后就可以用編譯后的正則表達式去匹配字符串
語法如下:
>>> help(re.compile) Help on function compile in module re: compile(pattern, flags=0) Compile a regular expression pattern, returning a pattern object.
>>>
pattern : 一個字符串形式的正則表達式
flags :可選,表示匹配模式,比如忽略大小寫,多行模式等
示例:
>>> test_pattern = re.compile(r'\d{2}') # 編譯一個正則表達式,並將其賦給一個變量 >>> m = test_pattern.match('12bc34') # 使用編譯后的正則表達式對象直接匹配字符串 >>> m <_sre.SRE_Match object; span=(0, 2), match='12'>
>>> test_pattern = re.compile(r'a\w+') # 生成一個正則表達式對象(這里是匹配以a開頭的單詞) >>> m = test_pattern.findall('apple,blue,alone,shot,attack') # 使用findall()函數匹配所有滿足匹配規則的子串 >>> m ['apple', 'alone', 'attack']
2.group()和groups()
一般用match()或search()函數匹配,得到匹配對象后,需要用group()方法獲得匹配內容;同時也可以提取分組截獲的字符串(正則表達式中()用來分組)
示例:
>>> pattern = re.compile(r'^(\d{3})-(\d{3,8})$') # 匹配一個3位數開頭,然后一個-,然后跟着3-8位數字的字符串 >>> m = pattern.match('020-1234567') >>> m <_sre.SRE_Match object; span=(0, 11), match='020-1234567'> >>> m.group() # 顯示整個匹配到的字符 '020-1234567' >>> m.group(0) # 同樣是顯示整個匹配到的字符 '020-1234567' >>> m.group(1) # 提取第1個分組中的子串 '020' >>> m.group(2) # 提取第2個分組中的子串 '1234567' >>> m.group(3) # 因為不存在第3個分組,所以這里會報錯:沒有這樣的分組 Traceback (most recent call last): File "<pyshell#73>", line 1, in <module> m.group(3) IndexError: no such group
>>> m.groups()
('020', '1234567')
>>>
2018-06-07 22:43:46