python正则表达式re模块详解
2019/7/13 21:50:54
本文主要是介绍python正则表达式re模块详解,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
快速入门
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
这篇关于python正则表达式re模块详解的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-24Python编程基础详解
- 2024-11-21Python编程基础教程
- 2024-11-20Python编程基础与实践
- 2024-11-20Python编程基础与高级应用
- 2024-11-19Python 基础编程教程
- 2024-11-19Python基础入门教程
- 2024-11-17在FastAPI项目中添加一个生产级别的数据库——本地环境搭建指南
- 2024-11-16`PyMuPDF4LLM`:提取PDF数据的神器
- 2024-11-16四种数据科学Web界面框架快速对比:Rio、Reflex、Streamlit和Plotly Dash
- 2024-11-14获取参数学习:Python编程入门教程