Regular expression to apply backspace characters

前端 未结 2 771
攒了一身酷
攒了一身酷 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条回答
  • 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.

    0 讨论(0)
  • 2021-01-13 23:53

    This is basically a variant of How can we match a^n b^n with Java regex?, so we could reuse its answer there:

    var regex = new Regex(@"(?:[^\b](?=[^\b]*((?>\1?)[\b])))+\1");
    Console.WriteLine(regex.Replace("Hello7\b World123\b\b\b", ""));
    

    Additionally, the .NET regex engine supports balancing groups, so we could use a different pattern:

    var regex = new Regex(@"(?<L>[^\b])+(?<R-L>[\b])+(?(L)(?!))");
    

    (This means:

    1. Match one or more non-backspaces, assigning them with the name "L",
    2. then followed one or more backspaces, assigning them with the name "R", with the condition that every "R" must have one corresponding "L",
    3. if there are any "L"s left, abandon the match (as (?!) matches nothing).

    )

    0 讨论(0)
提交回复
热议问题