Is there a way to decode q-encoded strings in Ruby?

前端 未结 6 712
星月不相逢
星月不相逢 2021-01-13 16:05

I\'m working with mails, and names and subjects sometimes come q-encoded, like this:

=?UTF-8?Q?J=2E_Pablo_Fern=C3=A1ndez?=

Is there a way t

6条回答
  •  Happy的楠姐
    2021-01-13 16:37

    I use this to parse email subjects:

    You could try the following:

    str = "=?UTF-8?Q?J=2E_Pablo_Fern=C3=A1ndez?="
    if m = /=\?([A-Za-z0-9\-]+)\?(B|Q)\?([!->@-~]+)\?=/i.match(str)
            case m[2]
            when "B" # Base64 encoded
              decoded = Base64.decode64(m[3])
            when "Q" # Q encoded
              decoded = m[3].unpack("M").first.gsub('_',' ')
            else
              p "Could not find keyword!!!"
            end
            Iconv.conv('utf-8',m[1],decoded) # to convert to utf-8
    end
    

提交回复
热议问题