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中的绝对路劲和相对路径,分享给大家,也给自己留个笔记 1、绝对路径 os.path.abspath("文件名"): 显示的是一个文件的绝对路劲 eg:...

Python3使用requests发闪存的方法

requests是一个python 轻量的http客户端库,相比python的标准库要优雅很多。接下来通过本文给大家介绍Python3使用requests发闪存的方法,一起学习吧。 使...

使用python对excle和json互相转换的示例

python 版本:2.7 只是读取excel的话可以直接使用xlrd 1、excle to json 代码如下 # -*-coding:utf8 -*- import xlrd f...

Python内置的字符串处理函数整理

str='python String function' 生成字符串变量str='python String function'字符串长度获取:len(str)例:print '%s l...

浅谈python numpy中nonzero()的用法

nonzero函数返回非零元素的目录。 返回值为元组, 两个值分别为两个维度, 包含了相应维度上非零元素的目录值。 import numpy as np A = np.mat...