#!/usr/local/bin/ruby -w class String def stripped! gsub!(/^[[:space:]]*|[[:space:]]*$/, '') # whitespace characters: [ \t\r\n\v\f] end # cf. http://en.wikipedia.org/wiki/Regular_expression def lstripped! sub!(/^[[:space:]]*/, '') end def rstripped! sub!(/[[:space:]]*$/, '') end def stripped_all! gsub!(/^[[:cntrl:]\x20]*|[[:cntrl:]\x20]*$/, '') # control characters: [\x00-\x1F\x7F] and space character: \x20 end # cf. http://en.wikipedia.org/wiki/ASCII#ASCII_control_characters def lstripped_all! sub!(/^[[:cntrl:]\x20]*/, '') end def rstripped_all! sub!(/[[:cntrl:]\x20]*$/, '') end def delete_cntrl! return self unless self =~ /[[:cntrl:]]/ gsub!(/[[:cntrl:]]/, '') #str = gsub!(/[[:cntrl:]]/, '') # alternative #str.nil? ? self : str end end p "".strip! #=> nil p "".stripped! #=> "" p "abc".strip! #=> nil p "abc".stripped! #=> "abc" p "abc\000".strip! #=> "abc" (!) p "abc\000".stripped_all! #=> "abc" p "abc\000\001".strip! #=> nil p "abc\000\001".stripped_all! #=> "abc" puts p "".gsub!(/[[:cntrl:]]/, '') #=> nil p "a".gsub!(/[[:cntrl:]]/, '') #=> nil p "".delete_cntrl! #=> "" p "a".delete_cntrl! #=> "a" text = <<-EOS \r \x00 this is an example \t\x11 text caf\303\251 \x20\x20\x20\x20 \r \f \011 \x10 \x07 \t\r\v\f abc \v\000 def \000 \x20\x20 \r \v \r EOS puts "\n\n\e[1mOriginal text:\e[m\n" text.each_line { |l| p l } puts puts "\n\e[1mString#stripped!\e[m\n" text.each_line do |l| l.stripped! p l end puts "\n\e[1mString#lstripped!\e[m\n" text.each_line do |l| l.lstripped! p l end puts "\n\e[1mString#rstripped!\e[m\n" text.each_line do |l| l.rstripped! p l end puts "\n\e[1mString#stripped_all!\e[m\n" text.each_line do |l| l.stripped_all! p l end puts "\n\e[1mString#lstripped_all!\e[m\n" text.each_line do |l| l.lstripped_all! p l end puts "\n\e[1mString#rstripped_all!\e[m\n" text.each_line do |l| l.rstripped_all! p l end puts "\n\e[1mString#delete_cntrl!\e[m\n" text.each_line do |l| l.delete_cntrl! #l.delete_cntrl!.stripped_all! p l end
You need to create an account or log in to post comments to this site.