如何迭代正则表达式匹配的分组?

huangapple go评论143阅读模式
英文:

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])

playground示例

英文:

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])

playground example

huangapple
  • 本文由 发表于 2017年5月5日 05:58:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/43793421.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定