内容来自textprocessinpython
re_show.pyimportre
defre_show(pat,s):
printre.compile(pat,re.M).sub("{\g}",s.rstrip()),'\n'
s='''Maryhadalittlelamb
AndeverywherethatMary
went,thelambwassure
togo'''
re_show('a',s)
M{a}ryh{a}d{a}littlel{a}mb.
Andeverywhereth{a}tM{a}ry
went,thel{a}mbw{a}ssure
togo.>>>fromre_showimportre_show
>>>s='''Specialcharactersmustbeescaped.*'''
>>>re_show(r'.*',s)
>>>re_show(r'\.\*',s)
>>>re_show('\\\\',r'Python\escaped\pattern')
>>>re_show(r'\\',r'Regex\escaped\pattern')
>>>re_show(r'^Mary',s)
>>>re_show(r'Mary$',s)
>>>re_show(r'$','Maryhadalittlelamb')
>>>re_show(r'.a',s)
>>>re_show(r'(Mary)()(had)',s)
>>>re_show(r'\(.*\)','spam(andeggs)')
>>>re_show(r'[a-z]a',s)
>>>re_show(r'[^a-z]a',s)
>>>s2='Thepetstoresoldcats,dogs,andbirds.'
>>>re_show(r'cat|dog|bird',s2)
>>>s3='=firstfirst=#=secondsecond=#=first=#=second='
>>>re_show(r'=first|second=',s3)
>>>re_show(r'(=)(first)|(second)(=)',s3)
>>>re_show(r'=(first|second)=',s3)
>>>s='''Matchwithzerointhemiddle:@@
...Subexpressionoccurs,but...:@=!=ABC@
...Lotsofoccurrences:@=!==!==!==!==!=@
...Mustrepeatentirepattern:@=!==!=!==!=@'''
>>>re_show(r'@(=!=)*@',s)
>>>s='''AAAD...ABBBBCD...BBBCD...ABCCD...AAABBBC'''
>>>re_show(r'A+B*C?D',s)
>>>s2='''aaaaabbbbbccccc...aaabbbccc...aaaaabbbbbbbbbbbbbbccccc'''
>>>re_show(r'a{5}b{,6}c{4,8}',s2)
>>>re_show(r'a+b{3,}c?',s2)
>>>re_show(r'a{5}b{6,}c{4,8}',s2)
>>>s2='''jklabcxyz
...jklxyzabc
...jklabcabc
...jklxyzxyz
...'''
>>>re_show(r'(abc|xyz)\1',s2)
>>>re_show(r'(abc|xyz)(abc|xyz)',s2)
>>>re_show(r'(?Pabc|xyz)(?P=let3)',s2)
>>>s2='''--Iwanttomatchthewordsthatstart...--with'th'andendwith's'....this...thus...thistle...thislinematchestoomuch...'''>>>re_show(r'th.*s',s2)
>>>s2='''--Iwanttomatchthewordsthatstart...--with'th'andendwith's'....this...thus...thistle...thislinematchestoomuch...'''>>>re_show(r'th[^s]*.',s2)
>>>re.search(r'(?Li)cat','TheCatintheHat').start()
>>>re.search(r'cat','TheCatintheHat',re.L|re.I).start()s='''--Iwanttomatchthewordsthatstart...--with'th'andendwith's'....thislinematchesjustright...this#thus#thistle'''>>>re_show(r'th.*s',s)>>>re_show(r'th.*?s',s)>>>s='A-xyz-37#B:abcd:142#C-wxy-66#D-qrs-93'>>>re_new(r'([A-Z])(?:-[a-z]{3}-)([0-9]*)',r'\1\2',s)>>>re_new(r'([A-Z])(-[a-z]{3}-)([0-9]*)',r'\1\2',s)>>>s="A-xyz-37#B:abcd:142#C-wxy-66#D-qrs-93">>>re_new(r'(?P[A-Z])(-[a-z]{3}-)(?P[0-9]*)',r'\g\g',s)>>>s='A-xyz37#B-ab6142#C-Wxy66#D-qrs93'>>>#AssertthatthreelowercaselettersoccurafterCAP-DASH>>>re_new(r'([A-Z]-)(?=[a-z]{3})([\w\d]*)',r'\2\1',s)>>>#AssertthreelowercaselettsdoNOToccurafterCAP-DASH...>>>re_new(r'([A-Z]-)(?![a-z]{3})([\w\d]*)',r'\2\1',s)>>>re_show('Man','ManhandledbyTheMan')>>>re_show('(?<!The)Man','ManhandledbyTheMan')