Regular expression to apply backspace characters

前端 未结 2 788
攒了一身酷
攒了一身酷 2021-01-13 23:19

I have a string coming from a telnet client. This string contains backspace characters which I need to apply. Each backspace should remove one previously typed character.

2条回答
  •  不要未来只要你来
    2021-01-13 23:37

    I wouldn't try to use a regular expression for this, since it's very impenetrable to read and I have the feeling that it's not even possible with plain regular expression without any perl-like regex magic-extensions. My suggestion would be something like (python like pseudocode):

    stack = []
    for char in str:
        if char == BACKSPACE and not stack.isEmpty():
            stack.pop()
        else:
            stack.push(char)
    
    result = ''.join(stack)
    

    It'S immediately clear what happens and how it works.

提交回复
热议问题