Skip to content

Instantly share code, notes, and snippets.

@satoyos
Created May 6, 2013 11:03
Show Gist options
  • Select an option

  • Save satoyos/5524521 to your computer and use it in GitHub Desktop.

Select an option

Save satoyos/5524521 to your computer and use it in GitHub Desktop.
"\u3042\u3063\u3061"のようなコードポイント文字列に変換されてしまった 残念なUTF-8文字列を、ちゃんとしたUTF-8文字列に戻す。 対象とするコードは、"\u00xx"から"\u7Fxx"まで。 # RSpecの出力文字列をきちんと読めるようにするために作成した。 # ruby -v # => ruby 2.0.0p0 (2013-02-24) [i386-mingw32] # rspec -v # => 2.13.1
# "\u3042\u3063\u3061"のようなコードポイント文字列に変換されてしまった
# 残念なUTF-8文字列を、ちゃんとしたUTF-8文字列に戻す。
# 対象とするコードは、"\u00xx"から"\u7Fxx"まで。
#
# RSpecの出力文字列をきちんと読めるようにするために作成した。
# ruby -v # => ruby 2.0.0p0 (2013-02-24) [i386-mingw32]
# rspec -v # => 2.13.1
module Handle_uXXXX
DOUBLE_QUOTED_REGEXP = /"(.+)"/
SINGLE_QUOTED_REGEXP = /'(.+)'/
def self.correct_point_coded_str(str)
str.force_encoding('UTF-8')
unless (m = DOUBLE_QUOTED_REGEXP.match(str)) && m[1] =~ /\\u/
return str
end
matches = str.scan(/\\u[0-7][0-9A-F]{3}/).uniq
matches.each_with_index do |match, idx|
num_string = (match.split(/\\u/))[1]
chr = num_string.to_i(16).chr('UTF-8')
str.gsub!(Regexp.new('\\'+match), chr)
end
str
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment