python正则表达式re模块详解

yipeiwu_com5年前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程序代码的几种方法总结

程序能一次写完并正常运行的概率很小,基本不超过1%。总会有各种各样的bug需要修正。有的bug很简单,看看错误信息就知道,有的bug很复杂,我们需要知道出错时,哪些变量的值是正确的,哪些...

解决Python设置函数调用超时,进程卡住的问题

背景: 最近写的Python代码不知为何,总是执行到一半卡住不动,为了使程序能够继续运行,设置了函数调用超时机制。 代码: import time import signal...

Mac 上切换Python多版本

Mac 上切换Python多版本

Mac上自带了Python2.x的版本,有时需要使用Python3.x版本做开发,但不能删了Python2.x,可能引起系统不稳定,那么就需要安装多个版本的Python。 1、安装Pyt...

Python基于csv模块实现读取与写入csv数据的方法

Python基于csv模块实现读取与写入csv数据的方法

本文实例讲述了Python基于csv模块实现读取与写入csv数据的方法。分享给大家供大家参考,具体如下: 通过csv模块可以轻松读取格式为csv的文件,而且csv模块是python内置的...

Python中的异常处理学习笔记

Python 是面向对象的语言,所以程序抛出的异常也是类。 常见的异常类 1.NameError:尝试访问一个没有申明的变量 2.ZeroDivisionError:除数为 0 3.Sy...