golang处理0x08不可见unicode字符

时间是个幻觉

在同步印象笔记的接口中报错,报错的基本信息大致如下:
golang An invalid XML character (Unicode: 0x8) was found

原因在于,文本中包含了unicode不可见字符。所以,目标很明确,将不可见字符过滤掉。

我使用了"unicode/utf8"来进行处理,因为我们的数据库默认字符也是utf-8的。看一下这个package的描述:

Package utf8 implements functions and constants to support text encoded in UTF-8. It includes functions to translate between runes and UTF-8 byte sequences. See https://en.wikipedia.org/wiki/UTF-8

应该支持的条件是UTF-8的文本,我感觉GBK的应该不支持。刚兴趣的可以留言告诉我。

我们看一下unicode对照表,我看到一篇格式比较端正的CSDN的文章,大家可以去看:ASCII码、Unicode编码对照表 —— ASCII控制字符 Unicode编码 字符编码的前世今生,我截个图吧:
part1
part2
这些都是不可见字符,都需要替换掉。

// 我手直接码的,可能有编辑错误,有问题大家自己动手改改
originStr := "等待处理的字符串"

// 将字符串转换为rune数组
srcRunes := []rune(originStr)

// 创建一个新的rune数组,用来存放过滤后的数据
dstRunes := make([]rune, 0, len(srcRunes))

// 过滤不可见字符,根据上面的表的0-32和127都是不可见的字符
for _, c := range srcRunes {
	if c >= 0 && c <= 31 {
		continue
	}
	if c == 127 {
		continue
	}
	dstRunes = append(dstRunes, c)
}

result := string(dstRunes)

没有对代码进行压测,也不知道性能怎么样,但感觉来看,应能应该不怎么样吧。

没有当下

rune是什么类型呢,看一下它的定义:

// rune is an alias for int32 and is equivalent to int32 in all ways. It is
// used, by convention, to distinguish character values from integer values.
type rune = int32
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值