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
热门推荐
6 保研的祝福语简短
10 年轻20岁祝福语简短
11 朋友结婚祝福语信息简短
12 女孩婚礼贺卡祝福语简短
13 30段点歌简短祝福语
14 虎年春节祝福语图文简短
15 写给后妈祝福语大全简短
16 简短回复生日祝福语
17 校长送毕业祝福语简短
18 毕业立体贺卡祝福语简短