网络编程
位置:首页>> 网络编程>> Python编程>> python使用正则表达式的search()函数实现指定位置搜索功能

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

作者:caimouse  发布时间:2023-08-08 09:26:01 

标签: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()函数实现指定位置搜索功能网站的支持!

来源:http://blog.csdn.net/caimouse/article/details/78262846

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com