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计算玩彩票赢钱概率

使用Python计算玩彩票赢钱概率

工具:Jupyter notebook + Anaconda 游戏规则:时时彩一种玩法是买尾号。2元一个数字,中奖是20元。每个数字出现的概率相等。 目前想到两种买法: 随机购买,...

python图片二值化提高识别率代码实例

python图片二值化提高识别率代码实例

这篇文章主要介绍了python图片二值化提高识别率代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 代码如下 import...

python使用pip安装模块出现ReadTimeoutError: HTTPSConnectionPool的解决方法

今天使用pip安装第三库时,有时会报错: pip._vendor.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(hos...

详解Python logging调用Logger.info方法的处理过程

详解Python logging调用Logger.info方法的处理过程

本次分析一下Logger.info的流程 1. Logger.info源码: def info(self, msg, *args, **kwargs): """ Log...

python使用分治法实现求解最大值的方法

本文实例讲述了python使用分治法实现求解最大值的方法。分享给大家供大家参考。具体分析如下: 题目: 给定一个顺序表,编写一个求出其最大值和最小值的分治算法。 分析: 由于顺序表的结构...