Python正则表达式自己错误复盘
前段时间温习正则表达式,想写一个用re库中search(每次找出第一个出现的字符的位置:span,起始点:start和终点:end)返回目标字符串所有的位置的函数(思路是每找一次就切掉end之前的字符串,重新再找一次),中间发生了错误,记录一下给自己看看:
我的循环的条件是tmp不是None就继续进行,并且在过程中使用了tmp,那么我就需要把tmp的赋值放在最后面,并且在最开始就要给tmp完整的功能(作为re.search的结构体的完整的功能),不然到最后切了最后一次就会出现tmp = None 的情况
import re
def many_search(string,pattern):
tmp = 0
begin = 0
string3 = string
record = []
end = 0
#initialize the parameters
while(tmp != None):
n = len(string3)
#update the length of the string
if(n==end):
break
#另一个错误,调用的时候应该使用更加一般的例子
string3 = string3[begin:n]
#update the string ,remove the part searched
tmp = re.search(pattern,string3)
#错误示范:如果结束条件为None这里将会报错
#pattern used in search must with 'r'
pos = tmp.span()
#return a tuple,contains the (begin,end)
pos = list(pos)
#tuple can't be edited directly
pos[0] = pos[0]+end
pos[1] = pos[1]+end
record.append(pos)
end = tmp.end()
begin = end+1
return record
print(many_search('sflsjld.djslfld.dsjf.jlsd.dfld',r'\b\w+ld\b'))
下面是我修改之后的函数:
def many_search(string, pattern):
tmp = re.search(pattern, string)
record = []
end = 0
while tmp:
pos = tmp.span()
pos = list(pos)
pos[0],pos[1] = pos[0]+end,pos[1]+end
record.append(pos)
end = tmp.end()
string = string[end:]
tmp = re.search(pattern, string)
return record