importres='''Life can be dreams,
Life can be great thoughts;
Life can mean a person,
Sitting in a count.'''r=re.compile('\\b(?P<first>\w+)a(\w+)\\b')# 编译正则表达式,匹配所有包含字母'a'的单词m=r.search(s)# c从头开始搜索,search()返回搜索到的第一个单词print(m)# <_sre.SRE_Match object at 0x100af58b0>print(m.groupdict())# {'first': 'c'}print(m.groups())# ('c', 'n')m=r.search(s,9)# 从第十个字符开始搜索print(m.group())# dreamsprint(m.group(1))# dreprint(m.group(2))# msprint(m.group(1,2))# ('dre', 'ms')print(m.groupdict())# {'first': 'dre'}print(m.groups())# ('dre', 'ms')
importres='''Life can be dreams,
Life can be great thoughts;
Life can mean a person,
Sitting in a court.'''r=re.compile('\\b(?P<first>\w+)a(\w+)\\b')# 编译正则表达式匹配含有字母"a"的单词m=r.search(s,9)# 从第十个字符开始搜索print(m.start())# 输出匹配到的子字符串的起始位置# 12print(m.start(1))# 输出第一组的起始位置# 12print(m.start(2))# 输出第二组的起始位置# 16print(m.end(1))# 输出第一组的子字符串结束位置# 15print(m.end())# 输出子字符串的结束位置# 18print(m.span())# 输出子字符串的开始和结束的位置# (12, 18)print(m.span(2))# 输出第二组子字符串的开始和结束的位置# (16, 18)