ruby UTF-8 中的字节序列无效(ArgumentError)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29877310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 06:42:39  来源:igfitidea点击:

Invalid byte sequence in UTF-8 (ArgumentError)

rubyutf-8error-handling

提问by Simplicity

I'm trying to run a Ruby script, and always getting an error on this line:

我正在尝试运行 Ruby 脚本,但总是在这一行出现错误:

file_content.gsub(/dr/i,'med')

Where I'm trying to replace "dr" by "med".

我试图用“med”替换“dr”的地方。

The error is:

错误是:

program.rb:4:in `gsub': invalid byte sequence in UTF-8 (ArgumentError)

Why is that, how can I fix this issue?

这是为什么,我该如何解决这个问题?

I'm working on a MAC OS X Yosemite machine, with Ruby 2.2.1p85.

我正在使用 Ruby 2.2.1p85 的 MAC OS X Yosemite 机器上工作。

回答by jon snow

Probably your string is not in UTF-8 format, so use

可能你的字符串不是 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

See "Ruby 2.0.0 String#Match ArgumentError: invalid byte sequence in UTF-8".

请参阅“ Ruby 2.0.0 String#Match ArgumentError:UTF-8 中的无效字节序列”。