First import the regexp package
import regexp
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)
There are different matching methods
| Method | Description | Signature |
|---|---|---|
| Match | Test a string for matching a byte slice | func Match(pattern string, b []byte) (matched bool, err error) |
| MatchString | Test 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 matches | Like the Find/FindString methods, just returning arrays of matches |
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
Create expression with
r, _ := regexp.Compile("[a-zA-Z0-9]+")
and use it in method form
r.MatchString(input)