Delete non-UTF characters from a string in Ruby?

前端 未结 7 1620
不思量自难忘°
不思量自难忘° 2021-02-05 01:24

How do I delete non-UTF8 characters from a ruby string? I have a string that has for example \"xC2\" in it. I want to remove that char from the string so that it becomes a valid

相关标签:
7条回答
  • 2021-02-05 02:18

    You could do it like this

    # encoding: utf-8
    
    class String
      def validate_encoding
        chars.select(&:valid_encoding?).join 
      end
    end
    
    puts "testing\xC2 a non UTF-8 string".validate_encoding
    #=>testing a non UTF-8 string
    
    0 讨论(0)
提交回复
热议问题