Python split string without splitting escaped character

后端 未结 10 1400
谎友^
谎友^ 2020-12-08 20:56

Is there a way to split a string without splitting escaped character? For example, I have a string and want to split by \':\' and not by \'\\:\'

http\\://ww         


        
10条回答
  •  一个人的身影
    2020-12-08 21:21

    There is no builtin function for that. Here's an efficient, general and tested function, which even supports delimiters of any length:

    def escape_split(s, delim):
        i, res, buf = 0, [], ''
        while True:
            j, e = s.find(delim, i), 0
            if j < 0:  # end reached
                return res + [buf + s[i:]]  # add remainder
            while j - e and s[j - e - 1] == '\\':
                e += 1  # number of escapes
            d = e // 2  # number of double escapes
            if e != d * 2:  # odd number of escapes
                buf += s[i:j - d - 1] + s[j]  # add the escaped char
                i = j + 1  # and skip it
                continue  # add more to buf
            res.append(buf + s[i:j - d])
            i, buf = j + len(delim), ''  # start after delim
    

提交回复
热议问题