Python语言技术文档

微信小程序技术文档

php语言技术文档

jsp语言技术文档

asp语言技术文档

C#/.NET语言技术文档

html5/css技术文档

javascript

点击排行

您现在的位置:首页 > 技术文档 > python入门

python使用正则表达式的search()函数实现指定位置搜索功能

来源:中文源码网    浏览:151 次    日期:2024-05-10 06:01:01
【下载文档:  python使用正则表达式的search()函数实现指定位置搜索功能.txt 】


python使用正则表达式的search()函数实现指定位置搜索功能
前面学习过search()可以从任意一个文本里搜索匹配的字符串,也就是说可以从任何位置里搜索到匹配的字符串。但是现实世界很复杂多变的,比如限定你只能从第100个字符的位置开始匹配,100个字符之前的不要匹配,这样的需求怎么样实现呢?来看下面的例子,它就是指定位置开始搜索:
#python 3.6
#蔡军生
#http://blog.csdn.net/caimouse/article/details/51749579
#
import re
text = 'This is some text -- with punctuation.'
pattern = re.compile(r'\b\w*is\w*\b')
print('Text:', text)
print()
pos = 0
while True:
match = pattern.search(text, pos)
if not match:
break
s = match.start()
e = match.end()
print(' {:>2d} : {:>2d} = "{}"'.format(
s, e - 1, text[s:e]))
# Move forward in text for the next search
pos = e
结果输出如下:
Text: This is some text -- with punctuation.
0 : 3 = "This"
5 : 6 = "is"
在这个例子里,实现一个低效的iterall()函数相同的功能。
总结
以上所述是小编给大家介绍的python使用正则表达式的search()函数实现指定位置搜索功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对中文源码网网站的支持!

相关内容