工作中經常要和字符串打交道。匹配搜索自然少不了,這是正則表達式的強項。
直接上代碼練習。代碼示例參考這裏,講的比較詳細。
正則表達式兩種等價用法,如果在一個程序中經常用到pattern,那麼推薦使用方法1。
方法1:prog = re.compile(pattern, flag) result = prog.match(string)
方法2:result = re.match(pattern, string)
Exp1:match
import re
pattern = re.compile(r'hello')
match = pattern.match('hello world')
if match:
print match.group()
pattern = re.compile(r'hello', re.I)
match = pattern.search('HeLLo world')
if match:
print match.group()
pattern = re.compile(r'\d+')
res = pattern.split('one1two2three3four4')
print res
Exp4: findall
pattern = re.compile(r'\d+')
res = pattern.findall('one1two2three3four4')
print res
Exp5:finditer
pattern = re.compile(r'\d+')
for res in pattern.finditer('one1two2three3four4'):
print res.group(),