Regular expression to apply backspace characters

前端 未结 2 798
攒了一身酷
攒了一身酷 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: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(@"(?[^\b])+(?[\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).

    )

提交回复
热议问题