importres='''Life can be good;
Life can be bad;
Life is mostly cheerful;
But sometimes sad.
'''r=re.compile(r'be(?=\sgood)')# 编译正则表达式,只匹配其后单词为'good'的'be'm=r.search(s)print(m)# <_sre.SRE_Match object at 0x10625e850>print(m.span())# 输出匹配到的单词在字符串的位置# (9, 11)print(r.findall(s))# ['be']r=re.compile('be')print(r.findall(s))# ['be', 'be']r=re.compile(r'be(?!\sgood)')# 重新编译,匹配之后的单词不为'good'的'be'm=r.search(s)print(m)# <_sre.SRE_Match object at 0x1007c6238>print(m.span())# (27, 29)r=re.compile(r'(?:can\s)be(\sgood)')# 使用组来匹配'be good'm=r.search(s)print(m)# <_sre.SRE_Match object at 0x1055b1648>print(m.groups())# (' good',)print(m.group(1))# good # good前面是有空格的哦r=re.compile(r'(?P<first>\w)(?P=first)')# 使用组名重复,此处匹配具有两个重复字母的单词print(r.findall(s))# ['o', 'e']r=re.compile(r'(?<=can\s)b\w*\b')# 匹配以字母'b'开头位于'can'之后的单词print(r.findall(s))# ['be', 'be']r=re.compile(r'(?<!can\s)b\w*\b')# 匹配以字母'b'开头不位于'can'之后的单词print(r.findall(s))# ['bad']r=re.compile(r'(?<!can\s)(?i)b\w*\b')# 重新编译,忽略大小写print(r.findall(s))# ['bad', 'But']