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'm trying to do this in a single replace using regular expression:
string txt = "Hello7\b World123\b\b\b";
txt = Regex.Replace(txt, ".\\\b", "", RegexOptions.ECMAScript);
Which results in "Hello World12". Of course, I want "12" to be removed too, but it obviously doesn't match my expression.
In some way, it should repeat replacing until there are no more matches. Any ideas on how to achieve this with a single regular expression?
A regex (regular expression) consists of a sequence of sub-expressions. In this example, [0-9] and + . The [...] , known as character class (or bracket list), encloses a list of characters. It matches any SINGLE character in the list.
Java regex - erase characters followed by \b (backspace)
\\. matches the literal character . . the first backslash is interpreted as an escape character by the Emacs string reader, which combined with the second backslash, inserts a literal backslash character into the string being read. the regular expression engine receives the string \. html?\ ' .
A dedicated symbol for "backspace" exists as U+232B ⌫ but its use as a keyboard label is not universal. The backspace is distinct from the delete key, which in paper media for computers would punch out all the holes to strike out a character, and in modern computers deletes text following it.
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).)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With