前面學習過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()函數實現指定位置搜索功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林站長站網站的支持!
新聞熱點
疑難解答