python正则表达式re模块全称_python正则表达式re模块详解

本文介绍了如何使用Python的re模块进行快速匹配,包括基本的正则表达式搜索、预编译模式和findall/finderiter的区别。通过实例演示了模式匹配和字符串查找的操作,并展示了使用预编译模式提高效率的优势。
摘要由CSDN通过智能技术生成

快速入门

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值