python正则表达式re模块详解
更新时间:2014年06月25日 11:04:02 投稿:hebedich
re 模块包含对正则表达式的支持,因为曾经系统学习过正则表达式,所以基础内容略过,直接看 python 对于正则表达式的支持。
快速入门
import re
pattern = 'this'
text = 'Does this text match the pattern?'
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]))
执行结果:
#python re_simple_match.py
Found "this"
in "Does this text match the pattern?"
from 5 to 9 ("this")
import re
# Precompile the patterns
regexes = [ re.compile(p) for p in ('this', 'that')]
text = 'Does this text match the pattern?'
print('Text: {0}\n'.format(text))
for regex in regexes:
if regex.search(text):
result = 'match!'
else:
result = 'no match!'
print('Seeking "{0}" -> {1}'.format(regex.pattern, result))
执行结果:
#python re_simple_compiled.py
Text: Does this text match the pattern?
Seeking "this" -> match!
Seeking "that" -> no match!
import re
text = 'abbaaabbbbaaaaa'
pattern = 'ab'
for match in re.findall(pattern, text):
print('Found "{0}"'.format(match))
执行结果:
#python re_findall.py
Found "ab"
Found "ab"
import re
text = 'abbaaabbbbaaaaa'
pattern = 'ab'
for match in re.finditer(pattern, text):
s = match.start()
e = match.end()
print('Found "{0}" at {1}:{2}'.format(text[s:e], s, e))
执行结果:
#python re_finditer.py Found "ab" at 0:2 Found "ab" at 5:7
相关文章
利用Pycharm + Django搭建一个简单Python Web项目的步骤
这篇文章主要介绍了利用Pycharm + Django搭建一个简单Python Web项目的步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2020-10-10
Numpy对数组的操作:创建、变形(升降维等)、计算、取值、复制、分割、合并
这篇文章主要介绍了Numpy对数组的操作:创建、变形(升降维等)、计算、取值、复制、分割、合并,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2019-08-08


最新评论