Welcome To Golang By Example

Golang Regex: Use a variable inside a Regular Expression

Table of Contents

Overview

The regexp.MustCompile function is used to compile the given regex string. So the input to the MustCompile function is a string only. And since it is a string we can concatenate any variable with the rest of the pattern.

For example

regex := `b+`
sampleRegexp := regexp.MustCompile("a" + regex)

So here we are doing concatenation to get the whole pattern

"a" + regex

Let’s see a running program for the same.

Program

package main

import (
	"fmt"
	"regexp"
)

func main() {
	regex := `b+`
	sampleRegexp := regexp.MustCompile("a" + regex)

	match := sampleRegexp.FindString("abb")
	fmt.Println(match)

}

Output

abb