1 回答

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 #,然后是一個或多個字母、數字或下劃線。
- 1 回答
- 0 關注
- 84 瀏覽
添加回答
舉報