gpt4 book ai didi

ruby-on-rails - Ruby 2.0.0 字符串#Match ArgumentError : invalid byte sequence in UTF-8

转载 作者:数据小太阳 更新时间:2023-10-29 06:27:37 25 4
gpt4 key购买 nike

我经常看到这种情况,但还没有想出一个优雅的解决方案。如果用户输入包含无效的字节序列,我需要能够让它不引发异常。例如:

# @raw_response comes from user and contains invalid UTF-8
# for example: @raw_response = "\xBF"
regex.match(@raw_response)
ArgumentError: invalid byte sequence in UTF-8

已经问了很多类似的问题,结果似乎是对字符串进行编码或强制编码。然而,这些都不适合我:

regex.match(@raw_response.force_encoding("UTF-8"))
ArgumentError: invalid byte sequence in UTF-8

regex.match(@raw_response.encode("UTF-8", :invalid=>:replace, :replace=>"?"))
ArgumentError: invalid byte sequence in UTF-8

这是 Ruby 2.0.0 的错误还是我遗漏了什么?

奇怪的是它似乎编码正确,但匹配继续引发异常:

@raw_response.encode("UTF-8", :invalid=>:replace, :replace=>"?").encoding
=> #<Encoding:UTF-8>

最佳答案

在 Ruby 2.0 中 encode method将字符串编码为其当前编码时是空操作:

Please note that conversion from an encoding enc to the same encoding enc is a no-op, i.e. the receiver is returned without any changes, and no exceptions are raised, even if there are invalid bytes.

这在 2.1 中发生了变化,其中还添加了 scrub method作为执行此操作的更简单方法。

如果您无法升级到 2.1,则必须编码成不同的编码并返回以删除无效字节,例如:

if ! s.valid_encoding?
s = s.encode("UTF-16be", :invalid=>:replace, :replace=>"?").encode('UTF-8')
end

关于ruby-on-rails - Ruby 2.0.0 字符串#Match ArgumentError : invalid byte sequence in UTF-8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24036821/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com