如何遍历正则表达式匹配组 [英] How to iterate through regex matching groups

查看:107
本文介绍了如何遍历正则表达式匹配组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我的数据如下:

name=peter 
age=40
id=99

我可以创建一个正则表达式

I can create a regex

(\w+)=(\w+)

要将名称,年龄和ID匹配到第1组,将peter,40、99匹配到第2组.但是,我想迭代甚至选择地遍历这些组.例如,

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.,

如果group1值是id,我想进行其他处理.所以算法就像

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

我想做的第二件事就是跳到匹配的group1的第三个实例,并获取键"id",而不是进行迭代.

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.

推荐答案

使用 FindAllStringSubmatch 来找到所有匹配项:

Use FindAllStringSubmatch to find all the matches:

pat := regexp.MustCompile(`(\w+)=(\w+)`)
matches := pat.FindAllStringSubmatch(data, -1) // matches is [][]string

像这样遍历匹配的组:

for _, match := range matches {
    fmt.Printf("key=%s, value=%s\n", match[1], match[2])
}

通过与match [1]比较来检查"id":

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

游乐场示例

这篇关于如何遍历正则表达式匹配组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆