Ruby -- looking for some sort of "Regexp unescape" method

Posted by RubyNoobie on Stack Overflow See other posts from Stack Overflow or by RubyNoobie
Published on 2010-04-08T18:36:37Z Indexed on 2010/04/08 19:03 UTC
Read the original article Hit count: 305

I have a bunch of strings that appear to have been double-escaped -- eg, I have

"\\014\"\\000\"\\016smoothing\"\\011mean\"\\022color\"\\011zero@\\016" but I want "\014"\000"\016smoothing"\011mean"\022color"\011zero@\016"

Is there a method I can use to unescape them? I imagine that I could make a regex to remove 1 backslash from every consecutive n backslashes, but I don't have a lot of regex experience and it seems there ought to be a "more elegant" way to do it.

For example, when I puts MyString it displays the output I'd like, but I don't know how I might capture that into a variable.

Thanks!

Edited to add context: I have this class that is being used to marshal / restore some stuff, but when I restore some old strings it spits out a type error which I've determined is because they weren't -- for some inexplicable reason -- stored as base64. They instead appear to be 'double-escaped', when I need them to be 'single-escaped' to get restored.

require 'base64'
class MarshaledStuff < ActiveRecord::Base

  validates_presence_of :marshaled_obj

  def contents
    obj = self.marshaled_obj
    return Marshal.restore(Base64.decode64(obj))
  end

  def contents=(newcontents)
    self.marshaled_obj = Base64.encode64(Marshal.dump(newcontents))
  end
end

© Stack Overflow or respective owner

Related posts about ruby

Related posts about strings