2

I am creating a webserver that people connect to using telnet. Some telnet-clients send data per-line, but others send each and every character as soon as it is typed. In the server, I cache these until a newline is typed. (And therefore we have a full line)

However, backspace characters, (\x08), are also sent and in the string. I would like to implement the backspace behaviour by replacing a character followed by a backspace with nothing.

However, what if a user uses backspace to remove more than one letter at a time?

is it possible to construct a regexp that removes an N amount of characters when followed by an N amount of backspaces?

For completeness sake, I'm using Ruby 2.2 .

Thanks.

Qqwy
  • 5,214
  • 5
  • 42
  • 83

1 Answers1

1

You can achive that with a recursive regex with a subroutine call:

str = "\bNewqaz\b\b\b car!!!\b\b\b."
puts str.gsub(/^[\b]+|([^\b](\g<1>)*[\b])/, '').gsub(/[\b]/,'B')
# => New car.

Note that .gsub(/[\b]/,'B') part is used for demo only, to show there are no backspace symbols left. See IDEONE demo.

An alternative approach is

loop do 
  str = str.gsub(Regexp.new("^\b+|[^\b]\b"), "")
  break if !str.include?("\b")
end 

See IDEONE demo, turning \bNewqaz\b\b\b car!!!\b\b\b. to New car.:

str = "\bNewqaz\b\b\b car!!!\b\b\b."
puts str.gsub(/\x08/, "B")
loop do 
  str = str.gsub(Regexp.new("^\b+|[^\b]\b"), "")
  break if !str.include?("\b")
end 
puts str
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Thank you! That makes a lot of sense. Also, thanks for the extra example on IDEONE. – Qqwy Jun 06 '15 at 20:06