簡體   English   中英

如何檢查字符是否為utf-8

[英]How to check whether the character is utf-8

如何通過ruby | ror檢查字符集是否采用utf-8編碼?

在Ruby和其他任何地方都沒有明確的方法來做到這一點:

str = 'foo' # start with a simple string
# => "foo" 
str.encoding
# => #<Encoding:UTF-8> # which is UTF-8 encoded
str.bytes.to_a
# => [102, 111, 111] # as you can see, it consists of three bytes 102, 111 and 111
str.encode!('us-ascii') # now we will recode the string to 8-bit us-ascii encoding
# => "foo" 
str.encoding
# => #<Encoding:US-ASCII> 
str.bytes.to_a
# => [102, 111, 111] # see, same three bytes
str.encode!('windows-1251') # let us try some cyrillic
# => "foo" 
str.encoding
# => #<Encoding:Windows-1251> 
str.bytes.to_a
# => [102, 111, 111] # see, the same three again!

當然,您可以對文本進行一些統計分析,並消除文本無效的編碼,但從理論上講,這不是可解決的問題。

檢查UTF-8有效性

對於大多數多字節編碼,可以以編程方式檢測無效字節序列。 由於Ruby默認情況下將所有字符串視為UTF-8 ,因此您可以檢查是否在有效的UTF-8給出了字符串:

# encoding: UTF-8
# -------------------------------------------
str = "Partly valid\xE4 UTF-8 encoding: äöüß"

str.valid_encoding?
   # => false

str.scrub('').valid_encoding?
   # => true

轉換編碼

此外,如果字符串不是有效的UTF-8編碼,但您知道實際的字符編碼,則可以將字符串轉換為UTF-8編碼。


有時,您最終處於這樣一種情況,即您知道輸入文件的編碼是UTF-8CP1252 (也稱為Windows-1252 )。
檢查它是哪種編碼並轉換為UTF-8(如有必要):

# encoding: UTF-8
# ------------------------------------------------------
test = "String in CP1252 encoding: \xE4\xF6\xFC\xDF"
File.open( 'input_file', 'w' ) {|f| f.write(test)}

str  = File.read( 'input_file' )

unless str.valid_encoding?
  str.encode!( 'UTF-8', 'CP1252', invalid: :replace, undef: :replace, replace: '?' )
end #unless
   # => "String CP1252 encoding: äöüß"

=======
筆記

  • 以編程方式可以檢測大多數多字節編碼,如UTF-8(在Ruby中, 參見:#valid_encoding? ),具有很高的可靠性。 僅16字節后,隨機字節序列有效UTF-8的概率僅為0.01% (相比之下,依靠UTF-8 BOM

  • 但是,不可能以編程方式檢測單字節編碼(如CP1252ISO-8859-1 )的有效性。 因此,上面的代碼片段不起作用,即檢測String是否是有效的CP1252編碼。

  • 盡管UTF-8作為網絡中的默認編碼越來越受歡迎,但CP1252和其他Latin1種口味在西方國家仍然非常流行,特別是在北美。 請注意,有幾個單字節編碼非常相似,但與CP1252 (又名Windows-1252 )略有不同。 例子: ISO-8859-1ISO-8859-15

"your string".encoding
 # => #<Encoding:UTF-8>

或者,如果你想要它的進步,

"your string".encoding.name == "UTF-8"
 # => true

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM