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.
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.
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:
(?!)
matches nothing).)