英文:
How to iterate through regex matching groups
问题
我的数据看起来像这样:
name=peter
age=40
id=99
我可以创建一个正则表达式:
(\w+)=(\w+)
将name、age和id匹配到group1,将peter、40和99匹配到group2。然而,我想要遍历这些组,并且可以有选择地遍历这些组。例如,
如果group1的值是"id",我想要执行不同的处理。所以算法如下:
//遍历所有的group1,如果我看到group1的值是"id",那么我将相应的group2键赋给另一个变量。例如,newVar = 99
我想要做的第二件事是直接跳到匹配的第三个group1实例,并提取出键"id",而不是遍历。
英文:
say my data looks like this:
name=peter
age=40
id=99
I can create a regex
(\w+)=(\w+)
To match name, age, and id into group1, and peter, 40, 99 into group two. However, I want to iterate and even selectively iterate through these groups. E.g.,
I want to do different processing if the group1 value is id. So the algorithm is like
//iterate through all the group1, if I see group1 value is "id", then I assign the corresponding group2 key to some other variable. E.g., newVar = 99
The second thing I want to do is to just jump to the third instance of the matching group1 and get the key "id" out instead of iterating.
答案1
得分: 4
使用FindAllStringSubmatch函数来查找所有匹配项:
pat := regexp.MustCompile(`(\w+)=(\w+)`)
matches := pat.FindAllStringSubmatch(data, -1) // matches是[][]string
通过以下方式遍历匹配的组:
for _, match := range matches {
fmt.Printf("key=%s, value=%s\n", match[1], match[2])
}
通过与match[1]进行比较来检查是否为"id":
for _, match := range matches {
if match[1] == "id" {
fmt.Println("the id is: ", match[2])
}
}
通过索引获取第三个匹配项:
match := matches[2] // 第三个匹配项
fmt.Printf("key=%s, value=%s\n", match[1], match[2])
英文:
Use FindAllStringSubmatch to find all the matches:
pat := regexp.MustCompile(`(\w+)=(\w+)`)
matches := pat.FindAllStringSubmatch(data, -1) // matches is [][]string
Iterate through the matched groups like this:
for _, match := range matches {
fmt.Printf("key=%s, value=%s\n", match[1], match[2])
}
Check for "id" by comparing with match[1]:
for _, match := range matches {
if match[1] == "id" {
fmt.Println("the id is: ", match[2])
}
}
Get the third match by indexing:
match := matches[2] // third match
fmt.Printf("key=%s, value=%s\n", match[1], match[2])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论