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

相关文章

python django中8000端口被占用的解决

python django中8000端口被占用的解决

1. 问题截图:(8000端口被占用) 2. 第一种是可能会打开了多个运行窗口右键关闭即可: 3. 第二种是在你运行python的主机上查询出python所有在执行的python文件...

简单谈谈python的反射机制

  对编程语言比较熟悉的朋友,应该知道“反射”这个机制。Python作为一门动态语言,当然不会缺少这一重要功能。然而,在网络上却很少见到有详细或者深刻的剖析论文。下面结合一个web路由的...

浅谈tensorflow1.0 池化层(pooling)和全连接层(dense)

池化层定义在tensorflow/python/layers/pooling.py. 有最大值池化和均值池化。 1、tf.layers.max_pooling2d max_pooli...

浅谈Python中重载isinstance继承关系的问题

判断继承关系 通过内建方法 isinstance(object, classinfo) 可以判断一个对象是否是某个类的实例。这个关系可以是直接,间接或抽象。 实例的检查是允许重载的,可...

python使用Plotly绘图工具绘制气泡图

python使用Plotly绘图工具绘制气泡图

今天来讲讲如何使用Python 绘图工具,Plotly来绘制气泡图。 气泡图的实现方法类似散点图的实现。修改散点图中点的大小,就变成气泡图。 实现代码如下: import plotl...