re.search(pattern, text)(关键词:Python/正则表达式/re)

先上代码吧:

import re

pattern = 'this'
text = 'Does this text match the pattern?'

match = re.search(pattern, text)

s = match.start()   # 5
e = match.end()     # 9

print 'Found "%s"\nin "%s"\nfrom %d to %d {"%s"}' % \
        (match.re.pattern, match.string, s, e, text[s:e])

'''
Found "this"
in "Does this text match the pattern?"
from 5 to 9 {"this"}
'''

re.search(pattern, text)函数,取模式pattern和要扫描的文本text作为输入,如果在要扫描的文本text中,找到这个模式pattern,则返回1个Match对象。如果未找到模式,search()将返回None。
每个Match对象包含有关匹配性质的信息,包括原输入字符串( match.string )、使用的正则表达式( match.re 还是 match.re.pattern ?)、模式在原字符串中出现的位置( match.start() 和 match.end() )。
start() 和 end() 方法可以给出字符串中的相应索引,指示与模式匹配的文本在字符串中出现的位置。

参考文献:
1. 《Python 标准库》 - 第1章 文本 - 1.3 re 正则表达式 - 1.3.1 查找文本中的模式(P9 - P10)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值