Welcome To Golang By Example

Menu
  • Home
  • Blog
  • Contact Us
  • Support this website
Menu

Golang Regex: Use a variable inside a Regular Expression

Posted on August 12, 2021August 12, 2021 by admin

Table of Contents

  • Overview
  • Program

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
  • go
  • golang
  • Follow @golangbyexample

    Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2025 Welcome To Golang By Example | Design: Newspaperly WordPress Theme