for i inrange(3):print(re.match(r"(air(craft|plane)|jet)","airplane")[i])#airplane #只要匹配成功,首项都是完整匹配项#airplane#planetry:for i inrange(3):print(re.match(r"(air(?:craft|plane)|jet)","airplane")[i])#?:关闭捕获except IndexError as err:print("IndexError: {0}".format(err))#airplane#airplane#IndexError: no such group
s ="eric1 = something\n"\
"eric2 = somewhere\n"\
"eric3 = somebody"try:for i inrange(10):print(re.match(r"(\w+ = .+\n?)+", s)[i])except IndexError as err:print("IndexError: {0}".format(err))#eric1 = something#eric2 = somewhere#eric3 = somebody#eric3 = somebody#IndexError: no such group
s ="eric1 = something\n"\
"eric2 = somewhere\n"\
"eric3 = somebody"try:for i inrange(10):print(re.match(r"(?:(\w+) = (.+)\n?)+", s)[i])except IndexError as err:print("IndexError: {0}".format(err))#eric1 = something#eric2 = somewhere#eric3 = somebody#eric3#somebody#IndexError: no such group
re.match(r"eric","eric1")#<re.Match object; span=(0, 4), match='eric'>
re.match(r"eric\b","eric1")#None
re.match(r"deric","deric1")#<re.Match object; span=(0, 5), match='deric'>
re.match(r"d\beric","deric1")#None
s ="I'm sorry, my son.\n Actually, actually, she is my daughter, and your sister..."
re.match(r".+(?<=son)", s)#<re.Match object; span=(0, 17), match="I'm sorry, my son">
s ="I'm sorry, my son.\n Actually, actually, she is my daughter, and your sister..."
re.match(r".+(?<!daugther)", s)#<re.Match object; span=(0, 18), match="I'm sorry, my son.">
import re
re.escape("\\")#'\\\\'
s ="eric1 = something\n"\
"eric2 = somewhere\n"\
"eric3 = somebody"try:for i inrange(10):print(re.findall(r"(?:(\w+) = (.+)\n?)+", s)[i])except IndexError as err:print("IndexError: {0}".format(err))#('eric3', 'somebody')#IndexError: list index out of range#从下面的例子可以明白什么是非交叠匹配
s ="bigbigericbigbig\n"\
"smallsmallericsmallsmall\n"\
"hardharderichardhard"
e = r"""(?x)(?i)
((?P<attr>big|small)(eric)\2)
"""
e = re.compile(e)
re.findall(e, s)#[('bigericbig', 'big', 'eric'), ('smallericsmall', 'small', 'eric')]