问题 Golang正则表达式与非拉丁字符


我需要熟练的地鼠提供一些建议。

我正在解析一些句子中的单词和我的单词 \w+ regexp适用于拉丁字符。然而,它完全失败了一些西里尔字符。

这是一个示例应用程序:

package main

import (
    "fmt"
    "regexp"
)

func get_words_from(text string) []string {
    words := regexp.MustCompile("\\w+")
    return words.FindAllString(text, -1)
}

func main() {
    text := "One, two three!"
    text2 := "Раз, два три!"
    text3 := "Jedna, dva tři čtyři pět!"
    fmt.Println(get_words_from(text))
    fmt.Println(get_words_from(text2))
    fmt.Println(get_words_from(text3))
}

它产生以下结果:

 [One two three]
 []
 [Jedna dva t i ty i p t]

它返回俄语的空值和捷克语的额外音节。 我不知道如何解决这个问题。有人可以给我一些建议吗?

或者也许有更好的方法将句子分成没有标点符号的单词?


9836
2018-05-27 12:42


起源

尝试 regexp.MustCompile("\\p{L}+") - Avinash Raj


答案:


\w 简写类只匹配ASCII字母 去正则表达式因此,您需要一个Unicode字符类 \p{L}

\w             单词字符(== [0-9A-Za-z_]

使用字符类来包含数字和下划线:

    regexp.MustCompile("[\\p{L}\\d_]+")

输出 演示

[One two three]
[Раз два три]
[Jedna dva tři čtyři pět]

11
2018-05-27 12:51



哇,我明白了。只是习惯使用\ w,而我需要单词。我的错。谢谢你的帮助! - Keir
奖金 - 如果你使用反引号,你不必双重逃避: regexp.MustCompile(`[\p{L}\d_]+`) - Nathan Osman
是的,当我不知道原始时,我发布了这个 Go中的字符串文字。 - Wiktor Stribiżew