我正在用 golang 编写一个正则表达式来捕获可能出现在不同语言中的主题标签。例如,显然是英语,但可能有拉丁语或阿拉伯语用户会尝试使用这些字符集创建主题标签。 我知道 unicode 字符类名称,但是如何一次使用多个字符而不为每个字符生成正则表达式?
示例代码:
r, err := regexp.Compile(`\B(\#[[:ascii:]]+\b)[^?!;]*`)
这将匹配 "#hello #قق"
并输出 []string{#hello, #قق}
但不匹配 "#قق"
最佳答案
我建议使用
\B#[\p{L}\p{N}\p{M}_]+
其中 [\p{L}\p{N}\p{M}_]
大致是 Unicode 感知的 \w
模式。 \p{L}
匹配任何 Uniciode 字母,\p{M}
匹配任何组合标记,\p{N}
匹配任何 Unicode数字。
参见Go demo :
package main
import (
"fmt"
"regexp"
)
func main() {
text := "#hello #ذوق #citroën"
r := regexp.MustCompile(`\B#[\p{L}\p{N}\p{M}_]+`)
res := r.FindAllString(text, -1)
for _, element := range res {
fmt.Println(element)
}
}
输出:
#hello
#ذوق
使用 text := "#قق"
, the output is #٩ق
.
请参阅regex demo .
关于regex - 如何匹配多种语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53150358/