How to iterate through regex matching groups

后端 未结 1 1948
予麋鹿
予麋鹿 2021-01-25 06:23

say my data looks like this:

name=peter 
age=40
id=99

I can create a regex

(\\w+)=(\\w+)

To match name, age,

相关标签:
1条回答
  • 2021-01-25 06:39

    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

    0 讨论(0)
提交回复
热议问题