標籤:樣本 color 字串 img lag Regex 字元 recent image
這一節主要學習一下compile()函數和group()方法
1. re.compile()
compile 函數用於編譯Regex,產生一個Regex( Pattern )對象,然後就可以用編譯後的Regex去匹配字串
文法如下:
>>> help(re.compile)Help on function compile in module re:compile(pattern, flags=0) Compile a regular expression pattern, returning a pattern object.
>>>
pattern : 一個字串形式的Regex
flags :可選,表示匹配模式,比如忽略大小寫,多行模式等
樣本:
>>> test_pattern = re.compile(r‘\d{2}‘) # 編譯一個Regex,並將其賦給一個變數>>> m = test_pattern.match(‘12bc34‘) # 使用編譯後的Regex對象直接匹配字串>>> m<_sre.SRE_Match object; span=(0, 2), match=‘12‘>
>>> test_pattern = re.compile(r‘a\w+‘) # 產生一個Regex對象(這裡是匹配以a開頭的單詞)>>> m = test_pattern.findall(‘apple,blue,alone,shot,attack‘) # 使用findall()函數匹配所有滿足匹配規則的子串>>> m[‘apple‘, ‘alone‘, ‘attack‘]
2.group()和groups()
一般用match()或search()函數匹配,得到匹配對象後,需要用group()方法獲得匹配內容;同時也可以提取分組截獲的字串(Regex中()用來分組)
樣本:
>>> 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
在python中使用Regex(二)