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

相关文章

numpy实现神经网络反向传播算法的步骤

numpy实现神经网络反向传播算法的步骤

一、任务 实现一个4 层的全连接网络实现二分类任务,网络输入节点数为2,隐藏层的节点数设计为:25,50,25,输出层2 个节点,分别表示属于类别1 的概率和类别2 的概率,如图所示。...

python利用requests库模拟post请求时json的使用教程

python利用requests库模拟post请求时json的使用教程

我们都见识过requests库在静态网页的爬取上展现的威力,我们日常见得最多的为get和post请求,他们最大的区别在于安全性上: 1、GET是通过URL方式请求,可以直接看到,明文传输...

Python 内置函数globals()和locals()对比详解

这篇文章主要介绍了Python globals()和locals()对比详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 Pytho...

Python针对给定字符串求解所有子序列是否为回文序列的方法

Python针对给定字符串求解所有子序列是否为回文序列的方法

本文实例讲述了Python针对给定字符串求解所有子序列是否为回文序列的方法。分享给大家供大家参考,具体如下: 问题: 给定一个字符串,得到所有的子序列,判断是否为回文序列 思路: 对字符...

opencv3/python 鼠标响应操作详解

opencv3/python 鼠标响应操作详解

鼠标回调函数: def setMouseCallback( windowName, #窗口名称 onMouse, #鼠标响应处理函数 param=None)...