出于某些测试目的,我需要一个包含无效 unicode 字符的字符串。如何在 Zsh 中创建这样的字符串?
Sté*_*las 16
我假设您的意思是 UTF-8 编码的 Unicode 字符。
这取决于您所说的invalid是什么意思。
invalid_byte_sequence=$'\x80\x81'
Run Code Online (Sandbox Code Playgroud)
这是一个字节序列,它本身在 UTF-8 编码中无效(UTF-8 编码字符中的第一个字节总是设置两个最高位)。但是,该序列可以在字符的中间看到,因此一旦连接到另一个无效序列(如$'\xe1'
. $'\xe1'
或者$'\xe1\x80'
他们自己也将是无效的,可以被视为一个截断的字符。
other_invalid_byte_sequence=$'\xc2\xc2'
Run Code Online (Sandbox Code Playgroud)
0xc2 字节将开始一个 2 字节字符,并且 0xc2 不能位于 UTF-8 字符的中间。因此在有效的 UTF-8 文本中永远找不到该序列。相同$'\xc0'
或$'\xc1'
哪些是从未出现在 UTF-8 编码中的字节。
对于\uXXXX
和\UXXXXXXXX
序列,我假设当前语言环境的编码是 UTF-8。
non_character=$'\ufffe'
Run Code Online (Sandbox Code Playgroud)
这是当前指定的 66 个非字符之一。
not_valid_anymore=$'\U110000'
Run Code Online (Sandbox Code Playgroud)
Unicode 现在仅限于最多 0x10FFFF 的代码点。最初设计为最多覆盖 0x7FFFFFFF(perl
也支持达到 0xFFFFFFFFFFFFFFFF 的变体)的 UTF-8 编码现在通常也仅限于此。
utf16_surrogate=$'\ud800'
Run Code Online (Sandbox Code Playgroud)
代码点 0xD800 到 0xDFFF 是为 UTF16 编码保留的代码点。所以这些代码点的 UTF-8 编码是无效的。
现在剩余的大部分代码点仍未在最新版本的 Unicode 中分配。
unassigned=$'\u378'
Run Code Online (Sandbox Code Playgroud)
较新版本的 Unicode 带有指定的新字符。例如,Unicode 8.0(2015 年 6 月发布)具有 ( U+1F917 ),但在早期版本中未分配。
unicode_8_and_above_only=$'\U1f917'
Run Code Online (Sandbox Code Playgroud)
一些测试uconv
:
$ printf %s $invalid_byte_sequence| uconv -x any-name
Conversion to Unicode from codepage failed at input byte position 0. Bytes: 80 Error: Illegal character found
Conversion to Unicode from codepage failed at input byte position 1. Bytes: 81 Error: Illegal character found
$ printf %s $other_invalid_byte_sequence| uconv -x any-name
Conversion to Unicode from codepage failed at input byte position 0. Bytes: c2 Error: Illegal character found
Conversion to Unicode from codepage failed at input byte position 1. Bytes: c2 Error: Truncated character found
$ printf %s $non_character| uconv -x any-name
\N{<noncharacter-FFFE>}
$ printf %s $not_valid_anymore| uconv -x any-name
Conversion to Unicode from codepage failed at input byte position 0. Bytes: f4 90 80 80 Error: Illegal character found
$ printf %s $utf16_surrogate | uconv -x any-name
Conversion to Unicode from codepage failed at input byte position 0. Bytes: ed a0 80 Error: Illegal character found
$ printf %s $unassigned | uconv -x any-name
\N{<unassigned-0378>}
$ printf %s $unicode_8_and_above_only | uconv -x any-name
\N{<unassigned-1F917>}
$
Run Code Online (Sandbox Code Playgroud)
使用 GNU grep
,您可以使用它grep .
来查看它是否可以在输入中找到一个字符:
l=(invalid_byte_sequence other_invalid_byte_sequence non_character
not_valid_anymore utf16_surrogate unassigned unicode_8_and_above_only)
for c ($l) print -r ${(P)c} | grep -q . && print $c
Run Code Online (Sandbox Code Playgroud)
这对我来说是:
non_character
not_valid_anymore
utf16_surrogate
unassigned
unicode_8_and_above_only
Run Code Online (Sandbox Code Playgroud)
也就是说,我grep
仍然认为其中一些无效、非字符或尚未分配的字符是(或包含)字符。YMMV 用于grep
其他实用程序的其他实现。