python正则表达式re模块详解

yipeiwu_com6年前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

相关文章

在Python中使用Mako模版库的简单教程

Mako是一个高性能的Python模板库,它的语法和API借鉴了很多其他的模板库,如Django、Jinja2等等。 基本用法 创建模板并渲染它的最基本的方法是使用 Template 类...

Python3实现的简单验证码识别功能示例

本文实例讲述了Python3实现的简单验证码识别功能。分享给大家供大家参考,具体如下: 这次的需求是自动登录某机构网站, 其验证码很具特色, 很适合做验证码识别入门demo, 先贴主要代...

Python实现的多进程和多线程功能示例

本文实例讲述了Python实现的多进程和多线程功能。分享给大家供大家参考,具体如下: 听了朋友说起,他们目前开发的测试框架,用python实现的分布式系统。虽然python的执行效率没有...

Python中类的定义、继承及使用对象实例详解

本文实例讲述了Python中类的定义、继承及使用对象的方法。分享给大家供大家参考。具体分析如下: Python编程中类的概念可以比作是某种类型集合的描述,如“人类”可以被看作一个类,然后...

Python3 合并二叉树的实现

Python3 合并二叉树的实现

题目要求:给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将他们的值相加作为节点...