Link Search Menu Expand Document

Go Regex Examples

First import the regexp package
import regexp

Matching

match, _ := regexp.MatchString("[a-zA-Z0-9]+", input)
match will be true if the pattern matches. To return the first match as string use
matchstr := regexp.FindString("([a-zA-Z0-9]+)", input)
To return all matches:
matches := regexp.FindAllString("([a-zA-Z0-9]+)", input)

Matching Methods

There are different matching methods
MethodDescriptionSignature
MatchTest a string for matching a byte slice
func Match(pattern string, b []byte) (matched bool, err error)
MatchStringTest a string for match another string
func MatchString(pattern string, s string) (matched bool, err error)
Find
FindIndex
FindSubmatch
FindSubmatchIndex
Find first byte slices match and return it
func (re *Regexp) Find(b []byte) []byte
func (re *Regexp) FindIndex(b []byte) (loc []int)
func (re *Regexp) FindSubmatch(b []byte) [][]byte
func (re *Regexp) FindSubmatchIndex(b []byte) []int
FindString
FindStringIndex
FindStringSubmatch
FindStringSubmatchIndex
Find first string match and return it
func (re *Regexp) FindString(s string) string
func (re *Regexp) FindStringIndex(s string) (loc []int)
func (re *Regexp) FindStringSubmatch(s string) []string
func (re *Regexp) FindStringSubmatchIndex(s string) []int
FindAll
FindAllIndex
FindAllString
FindAllStringIndex
FindAllStringSubmatch
FindAllStringSubmatchIndex
Like the Find/FindString methods, just returning all matchesLike the Find/FindString methods, just returning arrays of matches

Replacing

To replace text use ReplaceAll or ReplaceAllString
func (re *Regexp) ReplaceAll(src, repl []byte) []byte
func (re *Regexp) ReplaceAllString(src, repl string) string
e.g.
result := regexp.Compile("\s+").ReplaceAllString(input, " ")
to collapse all whitespaces

Precompiled expressions

Create expression with
r, _ := regexp.Compile("[a-zA-Z0-9]+")
and use it in method form
r.MatchString(input)