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

相关文章

OPENCV去除小连通区域,去除孔洞的实例讲解

OPENCV去除小连通区域,去除孔洞的实例讲解

一、对于二值图,0代表黑色,255代表白色。去除小连通区域与孔洞,小连通区域用8邻域,孔洞用4邻域。 函数名字为:void RemoveSmallRegion(Mat &Src, Ma...

解决Django连接db遇到的问题

解决Django连接db遇到的问题

1、django.db.utils.ConnectionDoesNotExist: The connection default doesn't exist 解决:第一个连接的命名一定...

详解DeBug Python神级工具PySnooper

PySnooper 在 GitHub 上自嘲是一个“乞丐版”调试工具(poor man's debugger)。 一般情况下,在编写 Python 代码时,如果想弄清楚为什么 Pytho...

python模拟鼠标拖动操作的方法

python模拟鼠标拖动操作的方法

本文实例讲述了python模拟鼠标拖动操作的方法。分享给大家供大家参考。具体如下: pdf中的书签只有页码,准备把现有书签拖到一个目录中,然后添加自己页签。重复的拖动工作实在无趣,还是让...

基于Django统计博客文章阅读量

如何精确地记录一篇文章的阅读量是一个比较复杂的问题,不过对于我们的博客来说,没有必要记录的那么精确。因此我们使用一种简单但有效的方式来记录博客文章的阅读量:文章每被浏览一次,则其阅读量...