如何将Ab9876543210转换为Ab9876543210?正则表达式有解决方案吗?谢谢。

test <- dput("Ab9876543210")

最佳答案

免责声明:以下内容可在我的计算机上使用,但由于我不能仅根据提供的示例来复制全角字符串,因此,根据我的问题版本,这是一个最佳猜测(将字符串粘贴到文本文件中,然后将其保存使用UTF-8编码,并使用指定为UTF-8的编码将其加载。

步骤1.阅读文本(我添加了半角版本以进行比较):

> test <- readLines("fullwidth.txt", encoding = "UTF-8")
> test
[1] "Ab9876543210" "Ab9876543210"


步骤2.验证全角和半角版本不相等:

# using all.equal()
test1 <- test[1]
test2 <- test[2]
> all.equal(test1, test2)
[1] "1 string mismatch"

# compare raw bytes
> charToRaw(test1)
 [1] ef bb bf ef bc a1 62 ef bc 99 ef bc 98 ef bc 97 ef bc 96 ef bc 95 ef
[24] bc 94 ef bc 93 ef bc 92 ef bc 91 ef bc 90
> charToRaw(test2)
 [1] 41 62 39 38 37 36 35 34 33 32 31 30


对于有兴趣的人,如果将原始字节版本粘贴到utf-8 decoder中作为十六进制输入,您会看到除了字母b(从第7个字节中的62映射)以外,其余字母由3个字节组成序列。此外,前3个字节的序列映射到“零宽度无间断空格字符”,因此在将字符串打印到控制台时不可见。

步骤3.使用Nippon包从全角转换为半角:

library(Nippon)
test1.converted <- zen2han(test1)

> test1.converted
[1] "Ab9876543210"

# If you want to compare against the original test2 string, remove the zero
# width character in front
> all.equal(substring(test1.converted, 2), test2)
[1] TRUE

07-26 09:42
查看更多