工作中经常要和字符串打交道。匹配搜索自然少不了,这是正则表达式的强项。
直接上代码练习。代码示例参考这里,讲的比较详细。
正则表达式两种等价用法,如果在一个程序中经常用到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(),