Home > Back-end >  golang regex to capture text between a quote and a /
golang regex to capture text between a quote and a /

Time:10-11

my strings:

12345:cluster/ecs52v-usw2-tst",
12345:cluster/test32-euw1-stg",

The output I'm looking for is:
ecs52v-usw2-tst
test32-euw1-stg

I have multiple cluster names that I'm trying to capture in a slice I've gotten it in ruby (?<=\/)(.*(tst|stg|prd))(?=") but I'm having trouble in golang. https://go.dev/play/p/DyYr3igu2CF

CodePudding user response:

package main

import (
    "fmt"
    "regexp"
)

func main() {
    var re = regexp.MustCompile(`(?mi)/(.*?)"`)
    var str = `cluster/ecs52v-usw2-tst",
cluster/ecs52v-usw2-stg",
cluster/ecs52v-usw2-prd",`

    for i, match := range re.FindAllStringSubmatch(str, -1) {
        fmt.Println(match[1], "found at line", i)
    }
}

CodePudding user response:

You could use FindAllStringSubmatch to find all submatches.

func main() {
    var re = regexp.MustCompile(`(?mi)(/(.*?)")`)
    var str = `cluster/ecs52v-usw2-tst",
cluster/ecs52v-usw2-stg",
cluster/ecs52v-usw2-prd",`

    matches := re.FindAllStringSubmatch(str, -1)
    for _, match := range matches {
        fmt.Printf("val = %s \n", match[2])
    }
}

Output

val = ecs52v-usw2-tst 
val = ecs52v-usw2-stg 
val = ecs52v-usw2-prd 

https://go.dev/play/p/_LRVYaM2r7z

  • Related