Table of contents
1.
Introduction
2.
MatchString
3.
Compile
4.
FindAllString
5.
FindAllStringIndex
6.
ReplaceAllStringFunc
7.
Split
8.
Few More Example
9.
FAQs
10.
Key Takeaways
Last Updated: Mar 27, 2024

Regex in Go

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Regex stands for a regular expression that is made up of a special sequence of characters that defines a search pattern which is used for matching specific text and for more advanced text manipulation. A built-in package called “regexp” is present in the Golang for such regular expressions, it contains a list of actions like replacing, validating, extracting, etc. The regexp package uses RE2 syntax standards. Some of the commonly used functions are :

MatchString

This function is used to check whether the string passed as a parameter contains any match of the regular expression pattern or not. The function returns a boolean value and an error, if any.

Syntax 

func MatchString(pattern string, s string)


Example

package main
  
import (
    "fmt"
    // import package
    "regexp"
)
  
func main() {
  
    // string in which the pattern is to be searched
    str1 := "CodingNinjas"
  
    // 1.returns true if the pattern is present
    // in the string
    match1, err := regexp.MatchString("Coding", str1)
    fmt.Println("Match Found:", match1, "   Error: ", err)
  
    // 2.returns false as the pattern is not present
    // in the string
    match2, err := regexp.MatchString("World", str1)
    fmt.Println("Match Found:", match2, "  Error: ", err)
  
    // throws an error
    // as the pattern is not valid
    match3, err := regexp.MatchString("Hel(lo", str1)
    fmt.Println("Match Found:", match3, "  Error: ", err)
}


Output

Match Found: true    Error:  <nil>
Match Found: false   Error:  <nil>
Match Found: false   Error:  error parsing regexp: missing closing ): `Hel(lo`

Compile

In order to store complicated regular expressions Compile() function is used. It parses a regular expression and returns a regexp object, if successful, which can be used to match against the text.

Syntax

func Compile(expression string) 


Example

package main

import (
    "fmt"
    "log"
    "regexp"
)

func main() {

    words := [...]string{"Seven", "five", "twelve", "eleven"}

    // can be reused later
    re, err := regexp.Compile(".eve")
    
    //check if error
    if err != nil {
        log.Fatal(err)
    }

    // check with every string
    for _, word := range words {

        found := re.MatchString(word)

        if found {
            fmt.Printf("%s matches\n", word)
        } else {
            fmt.Printf("%s does not match\n", word)
        }
    }
}


Output

Seven matches
five does not match
twelve does not match
eleven matches

FindAllString

This function is used to return a slice of all successive matches of the regular expression.

Example

package main

import (
    "fmt"
    "os"
    "regexp"
)

func main() {

    var message = `Boxes are cuboids. A box can be made of cardboard or any solid material. A box has 6 faces.`
    
    re := regexp.MustCompile("(?i)box(es)?")

    found := re.FindAllString(message, -1)

    if found == nil {
        fmt.Printf("no match found\n")
        os.Exit(1)
    }

    fmt.Printf("Matches found are : \n")
    for _, word := range found {
        fmt.Printf("%s \n", word)
    }

}


Output

Matches found are : 
Boxes 
box 
box

FindAllStringIndex

This function is used to return the first and last index of a slice of all successive matches of the regular expression.

Example

package main

import (
    "fmt"
    "regexp"
)

func main() {

    var message = `Boxes are cuboids. A box can be made of cardboard or any solid material. A box has 6 faces.`

    re := regexp.MustCompile("(?i)box(es)?")

    ind := re.FindAllStringIndex(message, -1)

    for _, i := range ind {
        match := message[i[0]:i[1]] // get the slice
        fmt.Printf("%s at %d:%d\n", match, i[0], i[1])
    }
}


Output

Boxes at 0:5
box at 21:24
box at 75:78

ReplaceAllStringFunc

This function is used to return a copy of a string in which all the matches of the regular expression have been replaced by the return value of that function.

Example

package main

import (
    "fmt"
    "regexp"
    "strings"
)

func main() {

    message := "Hello Coders!!!"

    re := regexp.MustCompile(`[aeiou]+`)

    fmt.Println(re.ReplaceAllStringFunc(message, strings.ToUpper))
}


Output

HEllO COdErs!!!

Split

This function is used to get substrings from a string, separated by the defined regular expression. 

Example

package main

import (
    "fmt"
    "log"
    "regexp"
    "strconv"
)

func main() {

    var data = `1, 2, 3, 4, 5, 6, 7, 8, 9, 10`

    sum := 0

    re := regexp.MustCompile(",\\s*")

    nums := re.Split(data, -1)

    for _, num := range nums {

        n, err := strconv.Atoi(num) // convert string into integer
        
        sum += n // add it to sum
        
        if err != nil {
            log.Fatal(err)
        }
    }

    fmt.Println("The sum of values is",sum)
}


Output

The sum of values is 55

Few More Example

FAQs

  1. What are the uses of using the regex package?
    The regexp package in Golang is used for various actions like filtering, replacing, validating, or extracting.
     
  2. What is MustCompile in Golang?
    The MustCompile method compiles the regular expression and returns its instance. But It will cause an error if the pattern is invalid.
     
  3. What should be passed as the second argument to the Split function to get the maximum number of substrings?
    The value which should be passed as the second argument to the Split function to get the maximum number of substrings is -1.

Key Takeaways

In this article, we have extensively discussed what regex is, what different functions are available in the regex package in Golang with examples and their implementation in Visual Studio Code.

We hope that this blog has helped you enhance your knowledge regarding regex in the Golang programming language and if you would like to learn more, check out our articles on what golang is, why it is popular among engineers, understanding the dynamic of Golang.

Do upvote our blog to help other ninjas grow. Happy Coding!”

Live masterclass