duanqianruan8448
2017-05-04 21:58 阅读 35
已采纳

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

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

    点赞 评论 复制链接分享

相关推荐