Python split string without splitting escaped character

后端 未结 10 1379
谎友^
谎友^ 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:43

    I think a simple C like parsing would be much more simple and robust.

    def escaped_split(str, ch):
        if len(ch) > 1:
            raise ValueError('Expected split character. Found string!')
        out = []
        part = ''
        escape = False
        for i in range(len(str)):
            if not escape and str[i] == ch:
                out.append(part)
                part = ''
            else:
                part += str[i]
                escape = not escape and str[i] == '\\'
        if len(part):
            out.append(part)
        return out
    

提交回复
热议问题