Signup/Sign In
PUBLISHED ON: MARCH 13, 2023

How to extract all regular expression matches from string with Go language?

In this tutorial, we will create a program in Go language to extract all matching regular expression from a provided string. We are going to use standard packages from Go languages library;

Import required packages (Golang):

  • fmt - Implement formatted input output in Go.
  • regexp - This package allows us to search using regular expressions.
package main

import (
	"fmt"
	"regexp"
)

Extract regex from string

Let's declare a variable containing the string to extract regex from.

func main() {
	str := "echo $((1+2)) $((?)))"
}

Now, we can use the regex package with MustCompile() function to define a regular expression. (assign a varible for further use and easy reading)

re := regexp.MustCompile(`\$\(\((.*?)\)\)`)

To extract all regular expression matches from a string a store that into a list varible use FindAllStringSubmatch(string. int) with the assign variable.

command := re.FindAllStringSubmatch(str, -1)

We can use a for loop to go through all matched patterns.

for i := range command {
    fmt.Println("Match found :", command[i][1])
}

Take a look at the final code:

package main

import (
	"fmt"
	"regexp"
)

func main() {

	str := "echo $((1+2)) $((?)))"

	re := regexp.MustCompile(`\$\(\((.*?)\)\)`)

	command := re.FindAllStringSubmatch(str, -1)

	for i := range command {
		fmt.Println("Message :", command[i][1])
	}
}



About the author:
Pradeep has expertise in Linux, Go, Nginx, Apache, CyberSecurity, AppSec and various other technical areas. He has contributed to numerous publications and websites, providing his readers with insightful and informative content.