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(PyS60)实现简单语音整点报时

本文实例为大家分享了python语音整点报时的具体代码,供大家参考,具体内容如下 主要的技术特殊点在于PyS60的定时器最多只能定2147秒。在手机上直接写的。 import e...

python try 异常处理(史上最全)

在程序出现bug时一般不会将错误信息显示给用户,而是现实一个提示的页面,通俗来说就是不让用户看见大黄页!!! 有时候我们写程序的时候,会出现一些错误或异常,导致程序终止. 为了处理异常,...

CentOS下Python3的安装及创建虚拟环境的方法

CentOS下Python3的安装及创建虚拟环境的方法

安装python3 一、安装需要编译的关联库 yum instal -y zlib zlib-devel   (根据自己系统的情况,安装需要的关联库,同样用yum安装...

Python Gluon参数和模块命名操作教程

本文实例讲述了Python Gluon参数和模块命名操作。分享给大家供大家参考,具体如下: Gluon参数和模块命名教程 在gluon里,每个参数和块都有一个名字(和前缀)。参数名可以由...

Python绑定方法与非绑定方法详解

本文实例为大家分享了Python绑定方法与非绑定方法,供大家参考,具体内容如下 定义: 绑定方法(绑定给谁,谁来调用就自动将它本身当作第一个参数传入):     1. 绑定到类的方法:用...