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向Excel中插入图片的简单实现方法

Python向Excel中插入图片的简单实现方法

本文实例讲述了Python向Excel中插入图片的简单实现方法。分享给大家供大家参考,具体如下: 使用Python向Excel文件中插入图片,这个功能之前学习xlwt的时候通过xlwt模...

Python中subprocess的简单使用示例

在c语言中,一个进程可以fork出一个子进程,并让这个子进程exec一个新的命令。在python中,我们通过标准库的subprocess包来fork一个子进程,并在子进程中运行一个新的程...

windows系统下Python环境的搭建(Aptana Studio)

windows系统下Python环境的搭建(Aptana Studio)

1、首先访问http://www.python.org/download/去下载最新的python版本。 2、安装下载包,一路next。 3、为计算机添加安装目录搭到环境变量,如图...

python类参数self使用示例

复制代码 代码如下:#coding:utf-8"""__new__和__init__到底是怎么一回事,看下面的代码如果类没有定义__new__方法,就从父类继承这个__new__方法。_...

Python multiprocessing模块中的Pipe管道使用实例

multiprocessing.Pipe([duplex]) 返回2个连接对象(conn1, conn2),代表管道的两端,默认是双向通信.如果duplex=False,conn1只能...