我有輸入字串,其中包含一些字符為 UTF-16 格式并用“ \u”轉義的文本。我試圖在 Perl 中將所有字串轉換為 UTF-8。例如,字串'Alice & Bob & Carol'可能在輸入中被格式化為:
'Alice \u0026 Bob \u0026 Carol'
為了進行我想要的轉換,我正在做...:
$str =~ s/\\u([A-Fa-f0-9]{4})/pack("U", hex($1))/eg;
...在我輸入包含 UTF-16 代理對的字串之前效果很好,例如:
'Alice \ud83d\ude06 Bob'
如何修改pack用于處理 UTF-16 代理對的上述代碼?我真的很想要一個pack無需使用任何其他庫(JSON::XS、Encode 等)即可使用的解決方案。
uj5u.com熱心網友回復:
pack/unpack不知道 UTF-16 文本,只知道 UTF-8(和 UTF-EBCDIC)。您必須手動解碼代理對,因為您不想使用模塊。
#!/usr/bin/env perl
use strict;
use warnings;
use open qw/:locale/;
use feature qw/say/;
my $str = 'Alice \ud83d\ude06 Bob \u0026 Carol';
# Convert surrogate pairs encoded as two \uXXXX sequences
# Only match valid surrogate pairs so adjacent non-pairs aren't counted as one
$str =~ s/\\u((?i)D[89AB]\p{AHex}{2}) # High surrogate in range 0xD800–0xDBFF
\\u((?i)D[CDEF]\p{AHex}{2}) # Low surrogate in range 0xDC00–0xDFFF
/chr( ((hex($1) - 0xD800) * 0x400) (hex($2) - 0xDC00) 0x10000 )/xge;
# Convert single \uXXXX sequences
$str =~ s/\\u(\p{AHex}{4})/chr hex $1/ge;
say $str;
輸出
Alice ?? Bob & Carol
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/494030.html
標籤:perl UTF-8 UTF-16 unicode 字符串 unicode 转义
