duanqianruan8448 2017-05-04 21:58
浏览 92
已采纳

如何遍历正则表达式匹配组

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条回答 默认 最新

  • douze2890241475 2017-05-05 01:38
    关注

    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
    ", 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
    ", match[1], match[2])
    

    playground example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀