Home > Net >  How can i make an array of regexes in Golang? [closed]
How can i make an array of regexes in Golang? [closed]

Time:10-02

i would like to create a an array of regexes like

regexes := []regexp.thingy{"[0-9]{0,40}" , "[a-z0-9]{0,5}"}

so i can just iterate over them and just match over a bunch of text, how can i do this?

CodePudding user response:

You can create an array of regular expressions and then iterate over each one, checking your string against the regular expression. This example assumes you want to detect whether a string matches any of the regular expressions.

package main

import (
    "fmt"
    "regexp"
)

func main() {
    fmt.Println(isMatch("something is awesome", []*regexp.Regexp{
        regexp.MustCompile("[0-9]{0,40}"),
        regexp.MustCompile("a-z0-9]{0,5}"),
    }))
}

func isMatch(str string, exprs []*regexp.Regexp) (matched bool) {
    for _, expr := range exprs {
        if expr.MatchString(str) {
            matched = true
            break
        }
    }
    return
}

CodePudding user response:

You can create a slice of compiled regex and iterate through it as such

r, _ := regexp.Compile("p([a-z] )ch")
    r2, _ := regexp.Compile(`a.b`)

    regexes := []*regexp.Regexp{r, r2}

    for _, v := range regexes {
        if !v.MatchString("peach"){
            fmt.Println("no match on ", v.String())
        } else {
            fmt.Println("match", v.String())
        }
    }

Playground example https://play.golang.org/p/ldV7rC_mqWp

  • Related