在 Go-Lang我需要從字符串中提取一個位于兩個定界符之間的子字符串,每對定界符將是一個鍵,子字符串將是它的值。一個簡單的例子:“可口可樂令人耳目一新<百事可樂>只是<不是>”兩個分隔符:< 和 >目標:extractMap:= map[string]string{"first":"pepsi", "second":"not"}我試圖捕獲兩者之間的數據的正則表達式\<(.*?)\>如何將提取的每個子字符串存儲在映射中,可以迭代以存儲提取的子字符串
1 回答

胡說叔叔
TA貢獻1804條經驗 獲得超8個贊
Go 沒有直接的方法來查找所有匹配項并將其作為地圖返回。您可以使用 regexp 包中的FindAllStringSubmatch來獲取所有匹配項和范圍。這是一個例子
str := "Coca Cola is refreshing < pepsi > is simply < not >"
r := regexp.MustCompile(`\<(.*?)\>`)
matches := r.FindAllStringSubmatch(str, -1)
for _, match := range matches {
if len(match) > 1 {
fmt.Println("Found match: ", match[1])
}
}
// Output
// Found match: pepsi
// Found match: not
- 1 回答
- 0 關注
- 144 瀏覽
添加回答
舉報
0/150
提交
取消