Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

go
golang
regex
regular expression

How to use RegEx in GoLang

Educative Answers Team

A regular expression is a sequence of characters that is used for searching and replacing text and pattern matching.

Note: This expression is not the property of just one particular programming language; instead, it is supported by multiple languages.

svg viewer

Regular expression patterns

There are certain expressions that need to be used to search and match patterns; some of these are given in the table below.

Expression Description
[] Used to find any of the characters or numbers specified between the brackets.
\d Used to find any digit.
\D Used to find anything that is not a digit.
\d+ Used to find any number of digits.
x* Used to find any number (can be zero) of occurrences of x.

RegEx in GoLang

The GoLang standard package for writing regular expressions is called regexp. The package uses RE2 syntax standards that are also used by other languages like Python, C, and Perl.

In order to use a regular expression in Go, it must first be parsed and returned as a regexp object.

package main
import (
	"fmt"
	"regexp"
)

func main() {
  re := regexp.MustCompile("ck$")
  fmt.Println(re.FindString("hack"))
}

1. FindString method

The FindString method returns the leftmost substring, thus matching the given pattern. If the pattern cannot be found, the method returns an empty string. The code below shows how to use this method.

package main
import (
  "fmt"
  "regexp"
)

func main() {
  re := regexp.MustCompile("et$")
  
  fmt.Println(re.FindString("cricket"))
  fmt.Println(re.FindString("hacked"))
  fmt.Println(re.FindString("racket"))
}

2. FindStringIndex method

The FindStringIndex method returns the starting and ending index of the leftmost match of the regular expression. If nothing is found, a null value is returned.

package main
import (
  "fmt"
  "regexp"
)

func main() {  
  re := regexp.MustCompile("tel")
  fmt.Println(re.FindStringIndex("telephone"))
  fmt.Println(re.FindStringIndex("carpet"))
  fmt.Println(re.FindStringIndex("cartel"))
}

3. FindStringSubmatch method

The FindStringSubmatch method returns the leftmost substring that matches the regex pattern. If no pattern is matched, a null value is returned. For example:

package main
import (
  "fmt"
  "regexp"
)

func main() { 
  re := regexp.MustCompile("p([a-z]+)ch")
  fmt.Println(re.FindStringSubmatch("peach punch"))
  fmt.Println(re.FindStringSubmatch("cricket"))
}

RELATED TAGS

go
golang
regex
regular expression
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring