确实是实践出真知,自己手打代码之后,以前停在理论上的东东,慢慢可以进入实战了。
比如,MATCH和SEARCH之间的区别。
#encoding: UTF-8 import re pattern = re.compile(r'hello') match = pattern.match('hello world!') if match: print match.group() pattern2 = re.compile(r'world') match2 = pattern2.search('hello world.') if match2: print match2.group() pattern3 = re.compile(r'\d+') re_string = 'one1two2three3four4' print pattern3.split(re_string) print pattern3.findall(re_string) for i in pattern3.finditer(re_string): print i.group(), print 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(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.end(2):",m.end(2) print "m.span(2):",m.span(2) print r"m.expand(r'\2 \1 \3'):",m.expand(r'\2 \1\3') p = re.compile(r'(\w+) (\w+)(?P<sign>.*)', re.DOTALL) print "p.pattern:", p.pattern print "p.flags:", p.flags print "p.groups:", p.groups print "p.groupindex:", p.groupindex p2 = re.compile(r'(\w+) (\w+)') s2 = 'i say, hello world!' print p2.sub(r'\2 \1', s2) print p2.subn(r'\2 \1', s2) def func(m): return m.group(1).title() + ' ' + m.group(2).title() print p2.sub(func, s2) print p2.subn(func, s2)
>>> ================================ RESTART ================================
>>>
hello
world
['one', 'two', 'three', 'four', '']
['1', '2', '3', '4']
1 2 3 4
m.string: hello world!!
m.re: <_sre.SRE_Pattern object at 0x00000000029F9A70>
m.pos: 0
m.endpos: 13
m.lastindex: 3
m.lastgroup: sign
m.group(1,2): ('hello', 'world')
m.groups(): ('hello', 'world', '!!')
m.groupdict(): {'sign': '!!'}
m.start(2): 6
m.end(2): 11
m.span(2): (6, 11)
m.expand(r'\2 \1 \3'): world hello!!
p.pattern: (\w+) (\w+)(?P<sign>.*)
p.flags: 16
p.groups: 3
p.groupindex: {'sign': 3}
say i, world hello!
('say i, world hello!', 2)
I Say, Hello World!
('I Say, Hello World!', 2)
>>>