我正在尝试运行 Ruby 脚本,但总是在这一行出现错误:
file_content.gsub(/dr/i,'med')
我试图用“med”替换“dr”的地方。
错误是:
program.rb:4:in `gsub': invalid byte sequence in UTF-8 (ArgumentError)
这是为什么,我该如何解决这个问题?
我正在使用 Ruby 2.2.1p85 的 MAC OS X Yosemite 机器上工作。
最佳答案
可能你的字符串不是UTF-8格式,所以使用
if ! file_content.valid_encoding?
s = file_content.encode("UTF-16be", :invalid=>:replace, :replace=>"?").encode('UTF-8')
s.gsub(/dr/i,'med')
end
参见“Ruby 2.0.0 String#Match ArgumentError: invalid byte sequence in UTF-8”。
关于ruby - UTF-8 中的无效字节序列 (ArgumentError),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29877310/