亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

識別推文消息中正確的標簽索引

識別推文消息中正確的標簽索引

Go
智慧大石 2022-11-15 10:47:05
我需要在 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)}
查看完整描述

1 回答

?
MMTTMM

TA貢獻1869條經驗 獲得超4個贊

該FindAllStringIndex()函數返回字節的位置,而不是符文。


您需要import "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 演示。


此外,#\w+是一個較短的模式來匹配 a #,然后是一個或多個字母、數字或下劃線。


查看完整回答
反對 回復 2022-11-15
  • 1 回答
  • 0 關注
  • 84 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號