re库中search返回目标字符串所有的位置的函数

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值