Java regex – erase characters followed by \b (backspace)


I have a string constructed from user keyboard types, so it might contain '\b' characters (backspaces).

I want to clean the string, so that it will not contain the '\b' characters, as well as the characters they are meant to erase. For instance, the string:

String str = "\bHellow\b world!!!\b\b\b.";

Should be printed as:

Hello world.

I have tried a few things with replaceAll, and what I have now is:

System.out.println(str.replaceAll("^\b+|.\b+", ""));

Which prints:

Hello world!!.

Single '\b' is handled fine, but multiples of it are ignored.

So, can I solve it with Java's regex?


I have seen this answer, but it seem to not apply for java's replaceAll.
Maybe I'm missing something with the verbatim string…

Best Solution

It can't be done in one pass unless there is a practical limit on the number of consecutive backspaces (which there isn't), and there is a guarantee (which there isn't) that there are no "extra" backspaces for which there is no preceding character to delete.

This does the job (it's only 2 small lines):

while (str.contains("\b"))
    str = str.replaceAll("^\b+|[^\b]\b", "");

This handles the edge case of input like "x\b\by" which has an extra backspace at the start, which should be trimmed once the first one consumes the x, leaving just "y".