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的装饰器? 网络上的定义:装饰器就是一函数,用来包装函数的函数,用来修饰原函数,将其重新赋值给原来的标识符,并永久的丧失原函数的引用。 最能说明装饰器的例子如下: 复制...

正则给header的冒号两边参数添加单引号(Python请求用)

正则给header的冒号两边参数添加单引号(Python请求用)

正则给header的冒号两边参数添加单引号(Python请求用) 直接从浏览器Chrome复制header值如下: Host: kyfw.12306.cn Connection:...

django之静态文件 django 2.0 在网页中显示图片的例子

小白,有错的地方,希望大家指正~ 使用的是django2.0 python3.6 1、首先,要在settings.py中设置 MEDIA_URL = '/media/' MEDIA_...

对numpy中轴与维度的理解

对numpy中轴与维度的理解

NumPy's main object is the homogeneous multidimensional array. It is a table of elements (usu...

python urllib urlopen()对象方法/代理的补充说明

python urllib urlopen()对象方法/代理的补充说明 urllib 是 python 自带的一个抓取网页信息一个接口,他最主要的方法是 urlopen(),是基于 py...