标签:
注意:Python3.X 的print要有括号, Python 2.x的不需要
放上学习时写的例子:
import re m = re.match(r‘(\w+) (\w+)(?P<sign>.*)‘, ‘hello world!‘) print("m.string:", m.string) print("m.re:", m.re) print("m.pos:", m.pos) print("m.endpos:", m.endpos) print("m.lastindex:", m.lastindex) print("m.lastgroup:", m.lastgroup) print("m.group():", m.group()) print("m.group(1,2):", m.group(1,2)) print("m.groups():", m.groups()) print("m.groupdict():", m.groupdict()) print("m.start(2):", m.start(2)) print("m.span(2):", m.span(2)) print(r"m.expand(r‘\g \g\g‘):", m.expand(r‘\2 \1\3‘)) #search 不一定从第0位开始匹配 pattern = re.compile(r‘world‘) match = re.search(pattern, ‘hello world!‘) if match: print(match.group()) #split 已pattern分割字符串 pattern = re.compile(r‘\d+‘) print(re.split(pattern, ‘one1two2three33four4‘)) #findall 以列表形式返回全部能匹配的子串 pattern = re.compile(r‘\d+‘) print(re.findall(pattern, ‘one1two2three33four4‘)) #finditer 返回一个顺序访问每一个匹配结果的迭代器 pattern = re.compile(r‘\d+‘) for m in re.finditer(pattern, ‘one1two2three3four4‘): print(m.group()) #替换 pattern = re.compile(r‘(\w+) (\w+)‘) s = ‘i say, hello world!‘ print(re.sub(pattern, r‘\2 \1‘, s)) def func(m): return m.group(1).title() + ‘ ‘ + m.group(2).title() print(re.sub(pattern, func, s)) #subn 比替换多返回了一个替换次数 print(re.subn(pattern, func, s))
标签:
原文地址:http://www.cnblogs.com/dplearning/p/4852869.html