我只想使用正则表达式在 Go 中查找 3 字节字符。 但它 panic
regexp: Compile(
\x{E29AA4}
): error parsing regexp: invalid escape sequence:\x{E29AA4
func get_words_from(text string) []string {
words := regexp.MustCompile(`\x{E29AA4}`)
return words.FindAllString(text, -1)
}
func main() {
text := "One,ВАПОЛтлдо⚤two ыаплд⚤ы ыапю.ы./\tавt𒀅hr𓀋ee!"
fmt.Println(get_words_from(text))
}
您可以试穿playground
最佳答案
解码 UTF-8 字节序列 E2 9A A4
,例如utf8.DecodeRune()
并在正则表达式中使用生成的 rune :
func get_words_from(text string) []string {
r, _ := utf8.DecodeRune([]byte{0xE2, 0x9A, 0xA4})
words := regexp.MustCompile(string(r))
return words.FindAllString(text, -1)
}
您也可以简单地convert字节 slice 到 string
(将其解释为 UTF-8 编码字节):
func get_words_from2(text string) []string {
s := string([]byte{0xE2, 0x9A, 0xA4})
words := regexp.MustCompile(s)
return words.FindAllString(text, -1)
}
或者在正则表达式字符串中使用等效的 unicode 代码点(即 0x26a4
):
func get_words_from3(text string) []string {
words := regexp.MustCompile("\u26a4")
return words.FindAllString(text, -1)
}
请注意,"\u26a4"
是解释后的字符串
文字,Go 编译器(而不是 regexp 包)不会对其进行转义。
所有示例均返回(尝试 Go Playground 上的示例):
[⚤ ⚤]
要过滤掉 UTF-8 中具有 3 个或更多字节的所有 rune ,您可以使用 for range
和 utf8.RuneLen()
:
text := "One,ВАПОЛтлдо⚤two ыаплд⚤ы ыапю.ы./\tавt𒀅hr𓀋ee!"
fmt.Println(text)
var out []rune
for _, r := range text {
if utf8.RuneLen(r) < 3 {
out = append(out, r)
}
}
fmt.Println(string(out))
此输出(在 Go Playground 上尝试):
One,ВАПОЛтлдо⚤two ыаплд⚤ы ыапю.ы./ авt𒀅hr𓀋ee!
One,ВАПОЛтлдоtwo ыаплды ыапю.ы./ авthree!
或者使用strings.Map()
,您在其中为此类 rune 返回 -1
,然后这些 rune 将在结果中被忽略:
out := strings.Map(func(r rune) rune {
if utf8.RuneLen(r) < 3 {
return r
}
return -1
}, text)
fmt.Println(string(out))
这输出相同。试试这个 Go Playground .
关于string - 如何通过正则表达式 3 和 4 字节 UTF-8 进行匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65273674/