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

相关文章

Windows下安装python2和python3多版本教程

Windows下安装python2和python3多版本教程

现在大家常用的桌面操作系统有:Windows、Mac OS、ubuntu,其中Mac OS 和 ubuntu上都会自带python。这里我们只介绍下Windows(我用的Win10)环境...

python通过robert、sobel、Laplace算子实现图像边缘提取详解

python通过robert、sobel、Laplace算子实现图像边缘提取详解

实现思路:   1,将传进来的图片矩阵用算子进行卷积求和(卷积和取绝对值)   2,用新的矩阵(与原图一样大小)去接收每次的卷积和的值   3,卷积图片所有的像素点后,把新的矩阵数据类型...

把vgg-face.mat权重迁移到pytorch模型示例

最近使用pytorch时,需要用到一个预训练好的人脸识别模型提取人脸ID特征,想到很多人都在用用vgg-face,但是vgg-face没有pytorch的模型,于是写个vgg-face....

python删除列表元素的三种方法(remove,pop,del)

remove 删除单个元素,删除首个符合条件的元素,按值删除,返回值为空 List_remove = [1, 2, 2, 2, 3, 4] print(List_remove.re...

Python 控制终端输出文字的实例

如下所示: class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[9...