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

相关文章

解决pandas展示数据输出时列名不能对齐的问题

列名用了中文的缘故,设置pandas的参数即可, 代码如下: import pandas as pd #这两个参数的默认设置都是False pd.set_option('dis...

python批量创建指定名称的文件夹

本文实例为大家分享了python批量创建指定名称的文件夹具体代码,供大家参考,具体内容如下 继删除多余文件之后,做了一些数据处理,需要重新保存数据,但文件夹的名称又不能改 所以只能创建新...

Python的lambda匿名函数的简单介绍

lambda函数也叫匿名函数,即,函数没有具体的名称。先来看一个最简单例子:复制代码 代码如下:def f(x):return x**2print f(4)Python中使用lambda...

简单谈谈python中的Queue与多进程

简单谈谈python中的Queue与多进程

最近接触一个项目,要在多个虚拟机中运行任务,参考别人之前项目的代码,采用了多进程来处理,于是上网查了查python中的多进程 一、先说说Queue(队列对象) Queue是python中...

python 求10个数的平均数实例

一,已知十个数,求平均数。 L=[1,2,3,4,5,6,7,8,9,10] a=sum(L)/len(L) print("avge is:", round(a,3) ) 运行结果...