java - Java 中的转义非拉丁字符

标签 java unicode

我有一个 Java 程序,它接受一个字符串并转义它,以便它可以安全地传递给 bash 中的程序。该策略基本上是转义提到的任何特殊字符 here并将结果用双引号引起来。

该算法非常简单——只需循环输入字符串并使用 input.charAt(i) 来检查当前字符是否需要转义。

此策略对于 surrogate pairs 未表示的字符非常有效。 ,但我担心字符串中是否嵌入了非拉丁字符或表情符号之类的内容。在这种情况下,如果我们假设表情符号是输入字符串中的第一个字符,则 input.charAt(0) 将为我提供第一个代码单元,而 input.charAt(1) 将返回第二个代码单元。我担心的是,其中一些代码单元可能会被解释为需要转义的特殊字符之一。如果发生这种情况,我会尝试转义其中一个代码单元,这将不可避免地混淆输入。

这样的事情可能吗?或者使用 input.charAt(i) 来完成类似的事情是否安全?

最佳答案

来自Java docs :

The Java 2 platform uses the UTF-16 representation in char arrays and in the String and StringBuffer classes. In this representation, supplementary characters are represented as a pair of char values, the first from the high-surrogates range, (\uD800-\uDBFF), the second from the low-surrogates range (\uDC00-\uDFFF).

来自UTF-16 Wikipedia page :

U+D800 to U+DFFF: The Unicode standard permanently reserves these code point values for UTF-16 encoding of the high and low surrogates, and they will never be assigned a character, so there should be no reason to encode them. The official Unicode standard says that no UTF forms, including UTF-16, can encode these code points.

来自charAt javadoc :

Returns the char value at the specified index. An index ranges from 0 to length() - 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.

If the char value specified by the index is a surrogate, the surrogate value is returned.

代理对代码点范围和特殊字符($、`、\等)存在的范围之间没有重叠,因为它们都使用 ASCII 字符映射(即它们都映射在 0 和 0 之间) 255)。

因此,如果我扫描包含表情符号(绝对超出补充字符范围)的字符串,我不会将代理对中的任何一项误认为是特殊字符。这是一个简单的测试程序: enter image description here enter image description here

关于java - Java 中的转义非拉丁字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60009732/

相关文章:

java - 找到一个能被 1 到 10 的所有数字整除的数字

css - 元素符号表现得像软连字符

c# - EPPlus 在 .xlsx 中以不正确的代码页给出 unicode 值

ruby - 如何将 UCS2 字符串转换为 UTF8?

sql-server-2005 - 导入包错误 - 无法在 Unicode 和非 Unicode 字符串数据类型之间转换

java - 除了 Apache Math Mean 之外,深层含义是什么?请参阅代码

java - 如何通过 jsf 迭代 Map<Map, Map> ?

java - 使用 jetty 网络服务器的网络套接字安全连接问题

java - HttpServletRequest 到达 Java REST API 后可以为 null 吗?

c - 如何使用 C API 从 ICU4C UChar * 转换为 char *(以打印 Unicode 字符串)?