import re
datepat = re.compile(r‘(\d+)/(\d+)/(\d+)‘)
m = datepat.match(‘11/27/2012‘)
print(m)
print(m.group(0))
print(m.group(1))
print(m.group(2))
print(m.group(3))
print(m.groups())
month, day, year = m.groups()
text = ‘Today is 11/27/2012. PyCon starts 3/13/2013.‘
datepat.findall(text)
for month, day, year in datepat.findall(text):
print(‘{}-{}-{}‘.format(year, month, day))
输出:
<_sre.SRE_Match object; span=(0, 10), match=‘11/27/2012‘>
11/27/2012
11
27
2012
(‘11‘, ‘27‘, ‘2012‘)
2012-11-27
2013-3-13
text = ‘@[email protected]$python‘
m = re.search(r"\w+", text)
if m:
print(m.group(0)) #python
else:
print(‘not match‘)
def test_findall_search():
str1 = ‘456abc789abc8910abc‘
re_str = re.compile(r‘\d+‘)
re_findall = re_str.findall(str1)
print(re_findall) #[‘456‘,‘789‘,‘8910‘]
re_search = re_str.search(str1)
print(re_search) #<_sre.SRE_Match object; span=(0, 3), match=‘456‘>
print(re_search.group(0)) #456
test_findall_search()