1. str ="abcdefg123213qwe",匹配以abc开头,以qwe结尾,要怎样写呢?
正解:m = re.match('^abc(.*?)qwe$','abcdefg123213qwe')
>>> m = re.match('^abc(.*?)qwe$','abcdefg123213qwe')
>>> m.group()
'abcdefg123213qwe'
>>> m.group(0)
'abcdefg123213qwe'
>>> m.group(1)
'defg123213'
>>> m.group(2)
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
m.group(2)
IndexError: no such group
2. contactInfo = 'Doe, John: 555-1212',进行分组匹配。
match = re.search(r'(\w+), (\w+): (\S+)', contactInfo)
>>> contactInfo = 'Doe, John: 555-1212'
>>> match = re.search(r'(\w+), (\w+): (\S+)', contactInfo)
>>> match.group(0)
'Doe, John: 555-1212'
>>> match.group()
'Doe, John: 555-1212'
>>> match.group(0)
'Doe, John: 555-1212'
>>> match.group(1)
'Doe'
>>> match.group(2)
'John'
>>> match.group(3)
'555-1212'
组的序数从1开始的原因是因为第0个组被预留来存放所有匹配对象