Python学习:re模块

正则表达式在文本中查找pattern正则表达式最常用的就是在文本中查找匹配项,比如:import repatterns = ['this', 'that']text = 'does this text match the patterns?'for pattern in patterns: print('looking for "%s" in "%s" ->' % (pat...
摘要由CSDN通过智能技术生成

正则表达式

在文本中查找pattern

正则表达式最常用的就是在文本中查找匹配项,比如:

import re

patterns = ['this', 'that']
text = 'does this text match the patterns?'

for pattern in patterns:
	print('looking for "%s" in "%s" ->' % (pattern, text))
	if re.search(pattern, text):
		print('found a match')
	else:
		print('no match')
        
#search()函数返回一个Match对象,如果没有找到匹配项,则函数返回None

search函数返回的Match对象包含了匹配的基本信息数据,包括初始的输入文本,匹配表达式,文本中匹配的起始位置与结束位置等。如:

import re

pattern = 'this'
text = 'does this text match the patterns?'

match = re.search(pattern, text)

s = match.start()
e = match.end()

print('found "%s" in "%s" from %d to %d ("%s")' % \
	(match.re.pattern, match.string, s, e, text[s:e]))

如果在程序中经常使用某个匹配表达式,可以首先编译匹配表达式,得到Regular Expression Objects,然后利用Regular Expression Objects继续匹配查找:

import re

regexes = [re.compile(p) for p in ['this', 'that']]
text = 'does this text match the patterns?'

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值