python正则表达式re模块详解

快速入门

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中,可以使用wave模块来读取双通道(立...
简介 一个用python实现的科学计算,包括: 1、一个强大的N维...
使用爬虫利器 Playwright,轻松爬取抖查查数据 我们先分析登...
轻松爬取灰豚数据的抖音商品数据 调用两次登录接口实现模拟登...
成功绕过阿里无痕验证码,一键爬取飞瓜数据 飞瓜数据的登录接...
一文教你从零开始入门蝉妈妈数据爬取,成功逆向破解数据加密...