regex - 识别推文消息中正确的主题标签索引

标签 regex go substring

我需要识别 Twitter 消息中的正确索引(各种语言、表情符号等)。

我找不到返回这些位置的解决方案,如下例所示。

import (
    "regexp"
    "testing"

    "github.com/stretchr/testify/require"
)

func TestA(t *testing.T) {
    text := "🇷🇺 [URGENT] Les forces de dissuasion #nucleaire de la #Russie"

    var re = regexp.MustCompile(`#([_A-Za-z0-9]+)`)

    pos := re.FindAllStringIndex(text, -1)

    // FindAllStringIndex returns
    // [0][43,53]
    // [1][60,67]

    // These are the expected positions.

    require.Equal(t, pos[0][0], 37) 
    require.Equal(t, pos[0][1], 47)

    require.Equal(t, pos[1][0], 54)
    require.Equal(t, pos[1][1], 61)
}

最佳答案

FindAllStringIndex()函数返回字节的位置,而不是 rune 。

您需要导入“unicode/utf8”并使用utf8.RuneCountInString(text[:pos[0][0]])等而不是pos[0][0] 以确保计算 Unicode 代码点而不仅仅是字节:

// You can edit this code!
// Click here and start typing.
package main

import (
    "regexp"
    "testing"
    "unicode/utf8"

    "github.com/stretchr/testify/require"
)

func TestA(t *testing.T) {
    text := "🇷🇺 [URGENT] Les forces de dissuasion #nucleaire de la #Russie"

    var re = regexp.MustCompile(`#\w+`)

    pos := re.FindAllStringIndex(text, -1)

    require.Equal(t, utf8.RuneCountInString(text[:pos[0][0]]), 37)
    require.Equal(t, utf8.RuneCountInString(text[:pos[0][1]]), 47)
    require.Equal(t, utf8.RuneCountInString(text[:pos[1][0]]), 54)
    require.Equal(t, utf8.RuneCountInString(text[:pos[1][1]]), 61)

}

请参阅Go demo .

此外,#\w+ 是一种较短的模式,用于匹配 # 以及一个或多个字母、数字或下划线。

关于regex - 识别推文消息中正确的主题标签索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71296214/

相关文章:

java - 使用java将英国邮政编码分成两个主要部分

java - 在Golang中初始化一个新类(Convert Java to Golang)

elasticsearch - 并发文件解析并插入到 Elastic Search 中

渲染后返回语句的 Golang lint

java - 我应该使用 substring 来避免 java 数据库中的某个字符串还是有其他方法可以绕过它?

c# - 从字符串中的给定 List<string> 中查找最长公共(public)匹配子字符串

java - 不止一种 IndexOf 可能性

php - 检查是否存在与正则表达式匹配的数组键

javascript - 在 JavaScript 中使用正则表达式验证货币金额

regex - 简化 htaccess 中的重定向