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正则匹配查询港澳通行证办理进度示例分享

复制代码 代码如下:import socketimport re '''广东省公安厅出入境政务服务网护照,通行证办理进度查询。分析网址格式为 http://www.gdcrj.com/w...

Django admin model 汉化显示文字的实现方法

1、将添加blog的后台基本操作 在blog文件夹下新建一个admin.py文件加入一下代码: from django.contrib import admin from djcm...

python数据处理实战(必看篇)

python数据处理实战(必看篇)

一、运行环境 1、python版本 2.7.13 博客代码均是这个版本 2、系统环境:win7 64位系统 二、需求 对杂乱文本数据进行处理 部分数据截图如下,第一个字段是原字段,后面3...

C#返回当前系统所有可用驱动器符号的方法

本文实例讲述了C#返回当前系统所有可用驱动器符号的方法。分享给大家供大家参考。具体如下: // The initial C# code for the "plain" WMI que...

python根据日期返回星期几的方法

本文实例讲述了python根据日期返回星期几的方法。分享给大家供大家参考。具体如下: 这个函数给定日期,输出星期几,至于0是星期一还是星期天,这和时区有关,反正我这里是0表示星期一...