python正则表达式re模块详解
快速入门
importre
pattern='this'
text='Doesthistextmatchthepattern?'
match=re.search(pattern,text)
s=match.start()
e=match.end()
print('Found"{0}"\nin"{1}"'.format(match.re.pattern,match.string))
print('from{0}to{1}("{2}")'.format(s,e,text[s:e]))
执行结果:
#pythonre_simple_match.py
Found"this"
in"Doesthistextmatchthepattern?"
from5to9("this")
importre
#Precompilethepatterns
regexes=[re.compile(p)forpin('this','that')]
text='Doesthistextmatchthepattern?'
print('Text:{0}\n'.format(text))
forregexinregexes:
ifregex.search(text):
result='match!'
else:
result='nomatch!'
print('Seeking"{0}"->{1}'.format(regex.pattern,result))
执行结果:
#pythonre_simple_compiled.py
Text:Doesthistextmatchthepattern?
Seeking"this"->match!
Seeking"that"->nomatch!
importre
text='abbaaabbbbaaaaa'
pattern='ab'
formatchinre.findall(pattern,text):
print('Found"{0}"'.format(match))
执行结果:
#pythonre_findall.py
Found"ab"
Found"ab"
importre
text='abbaaabbbbaaaaa'
pattern='ab'
formatchinre.finditer(pattern,text):
s=match.start()
e=match.end()
print('Found"{0}"at{1}:{2}'.format(text[s:e],s,e))
执行结果:
#pythonre_finditer.py Found"ab"at0:2 Found"ab"at5:7