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
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短