当前位置: 移动技术网 > IT编程>脚本编程>Python > python使用正则表达式的search()函数实现指定位置搜索功能

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

2017年12月01日  | 移动技术网IT编程  | 我要评论

淮阴师范教务处,十年 伴奏,九台在线

前面学习过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()函数实现指定位置搜索功能,希望对大家有所帮助

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网