python使用正则表达式的search()函数实现指定位置搜索功能
2019/7/13 22:40:35
本文主要是介绍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()函数实现指定位置搜索功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对找一找教程网网站的支持!
这篇关于python使用正则表达式的search()函数实现指定位置搜索功能的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-08有遇到过吗?同样的规则 Excel 中 比Python 结果大
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python