H
H
hitakiri2017-07-26 13:25:17
go
hitakiri, 2017-07-26 13:25:17

How to pass a variable in regexp.MustCompile condition?

There is a function:

func checkStr(a string, b string, c []string) {
  re := regexp.MustCompile("a(\\d+)b")
  for i := range c {
    fmt.Println(re.FindString(c[i]))
  }
}

The point is that you need to pass the variables a and b to the regexp condition.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pavlyuk, 2017-07-26
@hitakiri

First, it's more convenient to use backticks to avoid escaping the regular expression twice.
To insert a variable into a regular expression, its value must be escaped so as not to accidentally pass control characters. The regexp.QuoteMeta() function does this.
https://play.golang.org/p/LiNMvek6j5

func checkStr(a string, b string, c []string) {
  re := regexp.MustCompile(regexp.QuoteMeta(a) + `(\d+)` + regexp.QuoteMeta(b))
  for _, str := range c {
    fmt.Println(re.FindString(str))
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question